Conditional Count on a field

前端 未结 8 1825
庸人自扰
庸人自扰 2020-11-28 06:55

If I had a table like this:

jobId, jobName, Priority

Whereby Priority can be an integer between 1 to 5.

Since I would need this que

8条回答
  •  青春惊慌失措
    2020-11-28 07:24

    You could join the table against itself:

    select
       t.jobId, t.jobName,
       count(p1.jobId) as Priority1,
       count(p2.jobId) as Priority2,
       count(p3.jobId) as Priority3,
       count(p4.jobId) as Priority4,
       count(p5.jobId) as Priority5
    from
       theTable t
       left join theTable p1 on p1.jobId = t.jobId and p1.jobName = t.jobName and p1.Priority = 1
       left join theTable p2 on p2.jobId = t.jobId and p2.jobName = t.jobName and p2.Priority = 2
       left join theTable p3 on p3.jobId = t.jobId and p3.jobName = t.jobName and p3.Priority = 3
       left join theTable p4 on p4.jobId = t.jobId and p4.jobName = t.jobName and p4.Priority = 4
       left join theTable p5 on p5.jobId = t.jobId and p5.jobName = t.jobName and p5.Priority = 5
    group by
       t.jobId, t.jobName
    

    Or you could use case inside a sum:

    select
       jobId, jobName,
       sum(case Priority when 1 then 1 else 0 end) as Priority1,
       sum(case Priority when 2 then 1 else 0 end) as Priority2,
       sum(case Priority when 3 then 1 else 0 end) as Priority3,
       sum(case Priority when 4 then 1 else 0 end) as Priority4,
       sum(case Priority when 5 then 1 else 0 end) as Priority5
    from
       theTable
    group by
       jobId, jobName
    

提交回复
热议问题