将规范化为管道分隔列表

时间:2012-08-22 09:39:18

标签: sql sql-server

  

可能重复:
  Is there a way to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?

我有这样的标签:

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执行此操作?

3 个答案:

答案 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


SQL Fiddle Demo

答案 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)

See this SQLFiddle

另见: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