gpt4 book ai didi

sql - MS SQL 到 SQLite 语法

转载 作者:行者123 更新时间:2023-12-04 15:08:54 31 4
gpt4 key购买 nike

首先,我正在努力实现以下目标: enter image description here

我首先使用 MS SQL 弄清楚如何将标签对齐在一起。

如果您想重新创建未规范化的表,这里是架构。

CREATE TABLE unnormalized(
vendor_tag varchar(200),
vendor_tag_name varchar(200),
vendor_id int
);

INSERT INTO unnormalized
VALUES
('5,8,30,24','Burgers,Desserts,Fries,Salads',1),
('5','Burgers',2),
('8,42','Desserts,Mexican',3),
('1,5,30,16','American,Burgers,Fries,Sandwiches',4),
('1,5,30,16','American,Burgers,Fries,Sandwiches',5);

这是规范化表的代码

SELECT
--*
DISTINCT CAST(tag_id AS INT) as tag_id ,tag_name
FROM unnormalized
CROSS APPLY
(
(SELECT
value as tag_id,
ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn
FROM STRING_SPLIT(vendor_tag,',')
) a1
INNER JOIN
(SELECT
value as tag_name,
ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rn
FROM STRING_SPLIT(vendor_tag_name,',')
) a2
ON a1.rn = a2.rn
)
ORDER BY tag_id

现在我正在尝试使用 SQLite 重写这段代码。但是,存在一些差异,例如 SQLite 中没有“CROSS APPLY”和“STRING_SPLIT”。我环顾四周,发现 CROSS APPLY 可能类似于 SQLite 中的“CROSS JOIN”,并且可能使用类似这样的东西在它找到的第一个逗号处分隔字符串??

WITH split(vendor_id, vendor_tag, str) AS (
SELECT vendor_id, '', vendor_tag||',' FROM unnormalized
UNION ALL SELECT vendor_id,
substr(str, 0, instr(str, ',')),
substr(str, instr(str, ',')+1)
FROM split
WHERE str
)

SELECT vendor_id, vendor_tag
FROM split
WHERE vendor_tag
ORDER BY vendor_id;

最佳答案

在 SQLite 中,您可以使用递归 CTE 来完成:

WITH cte AS (
SELECT
vendor_tag,
vendor_tag_name,
SUBSTR(vendor_tag, 1, INSTR(vendor_tag || ',', ',') - 1) col1,
SUBSTR(vendor_tag_name, 1, INSTR(vendor_tag_name || ',', ',') - 1) col2
FROM unnormalized
UNION ALL
SELECT
SUBSTR(vendor_tag, LENGTH(col1) + 2),
SUBSTR(vendor_tag_name, LENGTH(col2) + 2),
SUBSTR(SUBSTR(vendor_tag, LENGTH(col1) + 2), 1, INSTR(SUBSTR(vendor_tag, LENGTH(col1) + 2) || ',', ',') - 1),
SUBSTR(SUBSTR(vendor_tag_name, LENGTH(col2) + 2), 1, INSTR(SUBSTR(vendor_tag_name, LENGTH(col2) + 2) || ',', ',') - 1)
FROM cte
WHERE LENGTH(vendor_tag) AND LENGTH(vendor_tag_name)
)
SELECT DISTINCT col1 vendor_tag, col2 vendor_tag_name
FROM cte
WHERE NOT (INSTR(col1, ',') OR INSTR(col2, ',')) AND (LENGTH(col1) AND LENGTH(col2))
ORDER BY vendor_tag + 0

参见 demo .
结果:

> vendor_tag | vendor_tag_name
> :--------- | :--------------
> 1 | American
> 5 | Burgers
> 8 | Desserts
> 16 | Sandwiches
> 24 | Salads
> 30 | Fries
> 42 | Mexican

关于sql - MS SQL 到 SQLite 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65565601/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com