SQL-如何分组,然后串联联接?

时间:2019-03-07 12:20:32

标签: sql sql-server

我在2个表之间建立了连接,但问题是我需要看到唯一的 CustomerId ,并用逗号分隔的 认证 ,例如,金,银,白金

这是我的SQL脚本

SELECT TOP (1000) 

Customer.CustomerID,
Customer.CustomerName,
Customer_Accreditations.AccreditationNumber


FROM 

Customer INNER JOIN
Customer_Accreditations ON Customer.CustomerID = 
Customer_Accreditations.CustomerID

使用此脚本的结果如下

CustomerID  CustomerName    AccreditationNumber
1272        Bree            Gold        
1272        Bree            Gold        
1272        Bree            Gold       
4071        Anneke          Silver      
4071        Anneke          Silver      
4071        Anneke          Platinum    

我想要的结果应该是

CustomerID  CustomerName    AccreditationNumber
1272        Bree            Gold,Gold,Gold        
4071        Anneke          Silver,Silver,Platinum

到目前为止,我只能获得唯一的值并连接认证 这是脚本:

SELECT CustomerID, displayname = 
STUFF((SELECT DISTINCT ',' + [AccreditationNumber]
               FROM Customer_Accreditations b 
               WHERE b.CustomerID = a.CustomerID
              FOR XML PATH('')), 1, 2, '')

FROM [DATABASE_NAME].[dbo].[Customer_Accreditations] a
GROUP BY CustomerID

这将返回以下结果

______________________________
|CustomerId  | displayname   |
|____________________________|
|1272        | Gold,Gold,Gold|
______________________________

这很好,但是如果我可以加入更多的Customer表/

非常感谢!

3 个答案:

答案 0 :(得分:0)

我认为您应该使用客户表来为每个客户获取一行。我认为这应该做您想要的:

SELECT c.*,
       STUFF( (SELECT ',' + [AccreditationNumber]
               FROM Customer_Accreditations ca
               WHERE ca.CustomerID = c.CustomerID
               FOR XML PATH('')
              ), 1, 2, ''
            ) as displayname
FROM [DATABASE_NAME].[dbo].[Customer] c;

答案 1 :(得分:0)

尝试一下

SELECT CustomerID,
       CustomerName ,
      STUFF(SELECT DISTINCT ', ' + AccreditationNumber
      FROM <Table> i
      WHERE i.CustomerID = o.CustomerID
      FOR XML PATH ('')),1,1,'') AS AccreditationNumber
FROM <Table> o

答案 2 :(得分:0)

SELECT a.CustomerID, a.CustomerName, displayname = 
STUFF((SELECT DISTINCT ',' + [AccreditationNumber]
FROM Customer_Accreditations b 
WHERE b.CustomerID = a.CustomerID
FOR XML PATH('')), 1, 2, '')

FROM [DATABASE_NAME].[dbo].[Customer] a
GROUP BY a.CustomerID, a.CustomerName