从SQL Server上的选定列获取不同值的串联列表的最有效方法是什么?
Col1 Col2 Col3
A 3 C23
A 3 C32
B 2 D12
C 1 C23
D 5 D12
D 5 C32
我的目标输出是一个表格如下:
ColumnNames DistinctValues
Col1 {A,B,C,D}
Col2 {1,2,3,5}
Col3 {C23,C32,D12}
如果我可以指定要查找哪些列,那将会很棒。
答案 0 :(得分:0)
首先,您需要取消数据
SELECT *
FROM yourtable
CROSS apply (VALUES(col1,'Col1'),
(Cast(col2 AS VARCHAR(50)),'Col2'),
(col3,'Col3')) tc(val, columnnames)
然后根据列名连接以获得结果
;WITH cte
AS (SELECT *
FROM yourtable
CROSS apply (VALUES(col1,'Col1'),
(Cast(col2 AS VARCHAR(50)),'Col2'),
(col3, 'Col3')) tc(val, columnnames))
SELECT DISTINCT columnnames,
'{'+Stuff(distinctvalues, 1, 1, '')+'}'
FROM cte a
CROSS apply(SELECT DISTINCT ',' + val
FROM cte b
WHERE a.columnnames = b.columnnames
FOR xml path('')) cs (distinctvalues)
另一种方法
SELECT 'Col1',
Stuff((SELECT DISTINCT ',' + col1
FROM yourtable
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
UNION ALL
SELECT 'Col2',
Stuff((SELECT DISTINCT ',' + Cast(col2 AS VARCHAR(50))
FROM yourtable
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
UNION ALL
SELECT 'Col3',
Stuff((SELECT DISTINCT ',' + col3
FROM yourtable
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, '')