SQL Group按逗号和句点串联

时间:2015-02-24 10:07:32

标签: sql-server-2008 tsql group-by

我有3个表,即客户,应用程序,代理。 3个表的结构和样本数据如下

Customer
==========
PKCustomerID    | CustomerName
1             | Test Customer1
2             | Test Customer 2

Application
============
PKApplicationID | ApplicationTitle | FKCustomerID 
1 | TestApplication1 | 1 
2 | TestApplication2 | 1 
3 | Test Application3 | 1

Agent
======
PKAgentID | AgentName | FKApplicationID | ComparableCode<br>
1 | AgentName 1 | 1 | AgentCode1
2 | AgentName 2 | 1 | AgentCode1 
3 | AgentName 3 | 2 | AgentCode2 

现在我需要一个类似于给定CustomerID的结果集

ComparableCode |  ApplicationNamer.AgentName | ApplicationCount 
AgentCode1 | TestApplication1.AgentName1,TestApplication1.AgentName2 | 2

我已经写了以下代码

SELECT ComparableCode, AgentName = 
STUFF((SELECT ', ' + AgentName
       FROM LNAgent b 
       WHERE b.ComparableCode = a.ComparableCode 
      FOR XML PATH('')), 1, 2, ''), COUNT(PKAgentID) [Application Count]
FROM LNAgent a
JOIN LNApplication app
ON app.PKApplicationID = a.FKApplicationID
JOIN LNCustomer cust on
cust.PKCustomerID = app.fkCustomerID
GROUP BY ComparableCode
ORDER BY [Application Count] DESC

以上查询给出了以下结果集

ComparableCode | ApplicationNamer.AgentName | AplicationCount
AgentCode1 | AgentName1, AgentName 2 | 2

我无法在ApplicationName.AgentName列中包含ApplicationName。

请帮助

1 个答案:

答案 0 :(得分:0)

如果我已正确理解您的要求,那么您需要在FOR XML子选择中包含LNApplication;

SELECT ComparableCode, AgentName = 
STUFF((SELECT ', ' + app2.ApplicationTitle + '.' + a2.AgentName
       FROM LNAgent a2 
       JOIN LNApplication app2
       ON app2.PKApplicationID = a2.FKApplicationID
       WHERE a2.ComparableCode = a.ComparableCode 
      FOR XML PATH('')), 1, 2, ''), COUNT(PKAgentID) [Application Count]
FROM LNAgent a
JOIN LNApplication app
ON app.PKApplicationID = a.FKApplicationID
JOIN LNCustomer cust on
cust.PKCustomerID = app.fkCustomerID
GROUP BY ComparableCode
ORDER BY [Application Count] DESC