SQL query to return a grouped result as a single row

后端 未结 2 1491
北恋
北恋 2021-01-25 02:59

If I have a jobs table like:

|id|created_at  |status    |
----------------------------
|1 |01-01-2015  |error     |
|2 |01-01-2015  |complete  |
|3 |01-01-2015           


        
2条回答
  •  滥情空心
    2021-01-25 03:56

    The following should work in any RDBMS:

    SELECT created_at, count(status) AS total,
           sum(case when status = 'error' then 1 end) as errors,
           sum(case when status = 'complete' then 1 end) as completed,
           sum(case when status = 'on hold' then 1 end) as on_hold
    FROM jobs 
    GROUP BY created_at;
    

    The query uses conditional aggregation so as to pivot grouped data. It assumes that status values are known before-hand. If you have additional cases of status values, just add the corresponding sum(case ... expression.

    Demo here

提交回复
热议问题