简体   繁体   中英

SQL query - order yes and no by quarter

I have following table:

id|overtime| date
--+--------+-----------
1 | yes    | 2017-03-10
2 | no     | 2017-07-16
3 | yes    | 2017-01-22
4 | no     | 2017-07-14

Now I want to sum the yes s and no s and order them by the quarter ( Q1 , Q2 , Q3 , Q4 ):

yes| no| quarter
---+---+---------------
13 |  4| Q1
2  |  5| Q2
8  | 14| Q3
12 | 12| Q4

My solution:

SELECT 
    (select count(*) As sum_yes from dashboard where overtime = 'Yes' ) as yes,
    (select count(*) As sum_no from dashboard where overtime = 'No' ) as no, 
    (SELECT quarter(date) as quarter from dashboard) 
group by quarter

I know it does not work. Very happy to get some help.

Use conditional aggregation:

select year(date) as yyyy, quarter(date) as q,
       sum(overtime = 'Yes') as yes,
       sum(overtime = 'No') as no
from dashboard
group by yyyy, q;

Note that this includes the year. I interpret "quarter" as distinguishing by year. If you want to combine data from multiple years, then remove that component.

MySQL treats a boolean as an integer in a numeric context, with "1" for true and "0" for false.

So you want one row per quarter...

...
FROM dashboard
GROUP BY quarter(date);

Then you'd like to get one column with the count of those row where overtime = 'Yes' :

SELECT
  COUNT(CASE WHEN overtime = 'Yes' THEN 1 END) as yes,
  ...

And one more for no

  ...
  COUNT(CASE WHEN overtime = 'No' THEN 1 END) as yes,
  ...

That's it. The case expression maps the matching rows to 1, while it maps the non mapping rows to null (due to the implied else null clause).

Just add the quarter column and you are done.

More about this technique: http://modern-sql.com/use-case/pivot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM