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

时间:2023-03-09 06:33:39
每天努力一点之SQL(二) count sum case when then group by

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了,就正确了。

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