每天努力一点之SQL(二) count sum case when then group by

时间:2014-06-04 21:10:46   收藏:0   阅读:513

1.

select sum(CASE WHEN A.[STATUS]=0 THEN 1 ELSE 0 end) as a1,
  sum(CASE A.[STATUS] WHEN 1 THEN 1 ELSE 0 end) as a2,
  sum(CASE A.[STATUS] WHEN 2 THEN 1 ELSE 0 end) as a3,

A.UserId,C.TrainId
  from CoursewareLogMiddle A join LessonDetail B
  on A.LessonId=B.Id
  join LessonClass C on B.ClassId=C.ClassId
  where a.UserId=9143 and c.TrainId=81
    group by A.UserId,C.trainId

 

行转列,虽然用到了case when then 但是也需要和group 结合使用。

刚一开始 sum 我写的是count 但是count 是会count 所有。

所以毅然改成sum了,就正确了。

这个方法可以计算出数量。

每天努力一点之SQL(二) count sum case when then group by,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!