2015-02-24 41 views
0

我有3个表,即客户,应用程序,代理。都为3代表的结构和样本数据如下SQL组通过逗号和句点连接字符串

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 

现在我需要一个结果是像对于给定的客户ID

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包含在ApplicationName.AgentName列中。

请帮助

回答

0

如果我理解您的要求正确,那么你需要包括LNApplication内部FOR XML子选择;

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 
相关问题