如何将这多行展平为一个?

时间:2017-01-12 02:44:32

标签: sql-server

我有这样的数据:(表名:Activities

ActivityId   CreatedOn  TypeId
1            2017-01-01 1
1            2017-01-02 1
1            2017-01-02 2
2            2017-01-01 3

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

TypeId   Name
1        Question
2        Answer
3        Comment

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

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

ActivityId   QuestionCount   AnswerCount   CommentCount
1            2               1             0
2            0               0             1

我知道答案可能非常简单,但出于某种原因,它已经躲过了我。

有任何帮助吗?提前谢谢。

1 个答案:

答案 0 :(得分:2)

简单的连接和条件聚合应该可以解决问题(我怀疑你过度思考了它)

Select ActivityID
      ,QuestionCount = sum(case when Name='Question' then 1 else 0 end)
      ,AnswerCount   = sum(case when Name='Answer'   then 1 else 0 end)
      ,CommentCount  = sum(case when Name='Comment'  then 1 else 0 end)
 From  Activities A
 Join  Types B on A.TypeId=B.TypeId
 Group By ActivityId

返回

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

您也可以尝试PIVOT

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