我有两个问题。第一个给我一个BusinessUnitIds列表以及每个的计数:
SELECT [b].[BusinessUnitId], COUNT([b].[BusinessUnitId]) AS bucount
FROM [dbo].[ComponentTeamBusinessUnit] [b]
WHERE [b].[GlobalClientFiscalYearId] = @GlobalClientFiscalYearId
AND [b].[ComponentTeamId] IN (SELECT items FROM [dbo].[fnSplit](@ComponentTeamIds, ','))
GROUP BY [b].[BusinessUnitId])
我想在此结果中获取BusinessUnitIds并将它们连接到第二个查询,该查询将检索与BusinessUnitIds关联的业务单位名称。如下所示:
Select [c].Name, [first query result].Count from [dbo].[BusinessUnit] [c]
INNER JOIN [first query result]
WHERE [c].BusinessUnitId = [first query result].BusinessUnitId
最终,我想要的是商家名称列表,以及每个商家名称的数量。我一直无法弄清楚如何做到这一点。有人可以帮忙吗?要在一个语句中执行这两个查询都是tops。谢谢。
答案 0 :(得分:1)
〔实施例:
SELECT [b].[BusinessUnitId],A.Name, COUNT([b].[BusinessUnitId]) AS bucount
FROM [dbo].[ComponentTeamBusinessUnit] [b]
LEFT JOIN NameTable as A
ON A.BusinessUnitId = b.BusinessUnitId
WHERE [b].[GlobalClientFiscalYearId] = @GlobalClientFiscalYearId
AND [b].[ComponentTeamId] IN (SELECT items FROM [dbo].[fnSplit](@ComponentTeamIds, ','))
GROUP BY [b].[BusinessUnitId],A.Name
如果表格是一对一,那将是整洁的,如果一对多,你会看到如下结果:
id name count
1 A 5
1 B 6
如果您想将id 1
分组,请获取:
id name count
1 A,B 11
您需要将FOR XML PATH()
与STUFF
或STRING_SPLIT
一起使用,这取决于您的实际情况。