我使用此查询并获取许多行中的公司名称列表(每行中的每个名称)
select distinct companyName from Companies
从每个名称我可以使用此查询来获取与该公司名称相关的另一个属性:
SELECT distinct
STUFF((SELECT ', '+ cn.name
from WMCCMCategories cn
INNER JOIN CategorySets uc
ON uc.categoryId = cn.categoryID
INNER JOIN KeyProcesses u
ON u.categorySetId = uc.setId
INNER JOIN Companies c
ON c.companyId = u.companyId
WHERE c.companyName = @companyName
ORDER BY cn.name FOR XML PATH('')), 1, 1, '') AS listStr
FROM WMCCMCategories cnn
Group by cnn.name
现在,我想在第一个查询中为每个名称应用该查询,因此我将第一个查询替换为@companyName:
SELECT distinct
STUFF((SELECT ', '+ cn.name
from WMCCMCategories cn
INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID
INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
INNER JOIN Companies c ON c.companyId = u.companyId
WHERE c.companyName in
(select distinct companyName from Companies)
ORDER BY cn.name FOR XML PATH('')), 1, 1, '') AS listStr
FROM
WMCCMCategories cnn
GROUP BY
cnn.name
但它会将所有结果打印在一行中。我需要的是每个公司名称在一行中的结果,我可以获得每个公司名称的每个属性。我怎么能修改才能得到它?
答案 0 :(得分:3)
写为:
SELECT distinct
c1.companyName,
STUFF((SELECT ', '+ cn.name
from WMCCMCategories cn
INNER JOIN CategorySets uc
ON uc.categoryId = cn.categoryID
INNER JOIN KeyProcesses u
ON u.categorySetId = uc.setId
INNER JOIN Companies c
ON c.companyId = u.companyId
WHERE c.companyName = c1.companyName
ORDER BY cn.name FOR XML PATH('')), 1, 1, '') AS listStr
FROM Companies c1
Group by c1.companyName