用于计算出现次数的SQL语句

时间:2017-01-17 16:12:04

标签: sql sql-server

我想运行一个sql查询来获取一个表的行和来自另一个表的对它的引用数。但是,引用的数量应该由第二个表中的字段拆分。

这是我简化的DB-Schema

TableA             TableB
------             ------
ID                 FK_A
                   GroupId 

我想查询TableA并计算TableB的引用元素,但由于它们的GroupId,分组。结果可能如下所示(Group1Group2Group3是TableB.GroupId中的值:

SELECT ID, ??? FROM TableA

ID Group1 Group2 Group3
1  1      0      7
2  3      3      9

我应该计算TableB中引用我的TableA的所有事件。

我真的不知道如何制作子查询或此处需要的任何内容。

更新 我不知道,哪个GroupId可以在TableB中。因此,多个计数语句都无法正常工作。

1 个答案:

答案 0 :(得分:0)

使用Conditional Aggregate

select FK_A,
       Count(case when GroupId = 1 then 1 end) as Group1,
       Count(case when GroupId = 2 then 1 end) as Group2,
       Count(case when GroupId = 3 then 1 end) as Group3
From TableB
Group by FK_A

如果组的数量未知,则

DECLARE @col VARCHAR(8000)= (SELECT ',' + Quotename(GroupId)
   FROM   TableB
   GROUP  BY GroupId
   FOR xml path (''))

SET @col = Stuff(@col, 1, 1, '')

DECLARE @sql VARCHAR(8000)='select * from TableB pivot (count(GroupId) for GroupId in ('
 + @col + ')) pv'

EXEC(@sql) 
相关问题