简体   繁体   English

SQL查询-按季度订购是和否

[英]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 ): 现在,我想对yesno求和,并按四分之一( Q1Q2Q3Q4 )对其进行排序:

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. MySQL在数值上下文中将布尔值视为整数,其中“ 1”为true,“ 0”为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' : 然后,您想获得一列,其中该行的计数为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). case表达式将匹配的行映射为1,同时将非映射行映射为null (由于隐含else null子句)。

Just add the quarter column and you are done. 只需添加四分之一列即可。

More about this technique: http://modern-sql.com/use-case/pivot 有关此技术的更多信息: http : //modern-sql.com/use-case/pivot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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