我有这样的标签:
cust acc ----------- a 1 b 2 b 3 c 4 c 5 c 6
我想将上面的反规范化为以下形式
cust acc --------------- a 1 b 2|3 c 4|5|6
请注意,acc列现在应包含任何客户的管道分隔的帐户列表。此外,客户可能的帐户数量也可以变化。
如何使用SQL执行此操作?
答案 0 :(得分:3)
试试这个:
SELECT cust, acc =
STUFF((SELECT '| ' +CAST( acc as varchar(20))
FROM <table> b
WHERE b.cust = a.cust
FOR XML PATH('')), 1, 2, '')
FROM <table> a
GROUP BY cust
答案 1 :(得分:1)
如果你想通过Cust(在MySQL中像Group_Concate
这样的东西)进行分组,那么在SQL Server中没有任何方法。
所以试试这个:
SELECT * FROM (
SELECT DISTINCT cust
FROM t
) table2
CROSS APPLY
(SELECT CASE ROW_NUMBER()
OVER(ORDER BY acc)
WHEN 1 THEN '' ELSE ' | ' END +
(cast(acc as varchar))
FROM t table3
WHERE table3.cust = table2.cust
ORDER BY acc
FOR XML PATH ('')
) table3(acc)
另见:Group columns into multiple rows and Group_concate like MySQL in SQL Server
答案 2 :(得分:0)
试试这个:
select cust,
STUFF((select '|'+cast(acc as varchar) from c1 where c1.cust = c2.cust for XML path('')),1,1,'') as acc from c1 c2
group by cust