Sql server 如何将多行展平为一行?

Sql server 如何将多行展平为一行?,sql-server,Sql Server,我有如下数据:(表名:活动) 其中,Type是一个查找值:(表名:Types) 基本上它是一个活动历史记录表 我想将上述表格转换为一个分组的类型总和行,每个ActivityId,如下所示: ActivityId QuestionCount AnswerCount CommentCount 1 2 1 0 2 0 0 1 我知道答案可能很

我有如下数据:(表名:
活动

其中,
Type
是一个查找值:(表名:
Types

基本上它是一个活动历史记录表

我想将上述表格转换为一个分组的类型总和行,每个
ActivityId
,如下所示:

ActivityId   QuestionCount   AnswerCount   CommentCount
1            2               1             0
2            0               0             1
我知道答案可能很简单,但出于某种原因,我一直没有找到答案


有什么帮助吗?提前感谢。

一个简单的连接和条件聚合应该可以做到这一点(我怀疑你想得太多了)

返回

ActivityID  QuestionCount   AnswerCount CommentCount
1           2               1           0
2           0               0           1
你也可以不用加入。。。只是可读性较差

Select ActivityID
      ,QuestionCount = sum(case when TypeId=1 then 1 else 0 end)
      ,AnswerCount   = sum(case when TypeId=2 then 1 else 0 end)
      ,CommentCount  = sum(case when TypeId=3 then 1 else 0 end)
 From  @Activities A
 Group By ActivityId
你也可以试试枢轴

Select ActivityID
      ,[1] as QuestionCount
      ,[2] as AnswerCount
      ,[3] as CommentCount
From  (Select ActivityId,TypeID,1 as Cnt From @Activities) A
Pivot (count(Cnt) For TypeId in ([1],[2],[3]) ) p

一个简单的连接和条件聚合应该可以做到这一点(我怀疑你想得太多了)

返回

ActivityID  QuestionCount   AnswerCount CommentCount
1           2               1           0
2           0               0           1
你也可以不用加入。。。只是可读性较差

Select ActivityID
      ,QuestionCount = sum(case when TypeId=1 then 1 else 0 end)
      ,AnswerCount   = sum(case when TypeId=2 then 1 else 0 end)
      ,CommentCount  = sum(case when TypeId=3 then 1 else 0 end)
 From  @Activities A
 Group By ActivityId
你也可以试试枢轴

Select ActivityID
      ,[1] as QuestionCount
      ,[2] as AnswerCount
      ,[3] as CommentCount
From  (Select ActivityId,TypeID,1 as Cnt From @Activities) A
Pivot (count(Cnt) For TypeId in ([1],[2],[3]) ) p

啊,聪明!我想得太多了:)谢谢!!顺便问一下,这是最有效的方式吗?我将不得不多次运行此查询,并且将有数百万条活动记录。不反对改变schema@RPM1984然后,我会选择第二个选项,而不选择加入。我想不出更快的办法了。啊,聪明!我想得太多了:)谢谢!!顺便问一下,这是最有效的方式吗?我将不得不多次运行此查询,并且将有数百万条活动记录。不反对改变schema@RPM1984然后,我会选择第二个选项,而不选择加入。我想不出更快的办法。