gpt4 book ai didi

SQL 查询以选择特定的列值并连接它们

转载 作者:搜寻专家 更新时间:2023-10-30 23:09:16 24 4
gpt4 key购买 nike

谁能帮我实现这个查询:我需要为每个值为 1 的字母携带所有 ID:

enter image description here

最佳答案

这是一个两步过程。首先,您需要将列转为行:

SELECT  upvt.ID, Letters
FROM T
UNPIVOT
( Value
FOR Letters IN ([A], [B], [C], [D], [E], [F])
) upvt
WHERE upvt.Value = 1;

这给出:

ID  Letters
10 A
10 C
10 E
10 F
...

然后您需要从这个结果中连接 ID:'

WITH Unpivoted AS
( SELECT upvt.ID, Letters
FROM T
UNPIVOT
( Value
FOR Letters IN ([A], [B], [C], [D], [E], [F])
) upvt
WHERE upvt.Value = 1
)
SELECT u.Letters,
IDs = STUFF(( SELECT ', ' + CAST(u2.ID AS VARCHAR(10))
FROM Unpivoted u2
WHERE u.Letters = u2.Letters
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
FROM Unpivoted u
GROUP BY u.Letters;

给出:

Letters IDs
A 10, 20, 50
B 20, 40
C 10, 20, 30, 40, 50
D 30, 40
E 10, 50
F 10, 20, 40

Example on SQL Fiddle

关于SQL 查询以选择特定的列值并连接它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204151/

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