[英]SQL query - order yes and no by quarter
我有下表:
id|overtime| date
--+--------+-----------
1 | yes | 2017-03-10
2 | no | 2017-07-16
3 | yes | 2017-01-22
4 | no | 2017-07-14
現在,我想對yes
和no
求和,並按四分之一( Q1
, Q2
, Q3
, Q4
)對其進行排序:
yes| no| quarter
---+---+---------------
13 | 4| Q1
2 | 5| Q2
8 | 14| Q3
12 | 12| Q4
我的解決方案:
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
我知道這行不通。 很高興獲得幫助。
使用條件聚合:
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;
請注意,這包括年份。 我將“季度”解釋為按年份區分。 如果要合並多年的數據,請刪除該組件。
MySQL在數值上下文中將布爾值視為整數,其中“ 1”為true,“ 0”為false。
所以你每季度要排一行...
...
FROM dashboard
GROUP BY quarter(date);
然后,您想獲得一列,其中該行的計數為overtime = 'Yes'
:
SELECT
COUNT(CASE WHEN overtime = 'Yes' THEN 1 END) as yes,
...
還有一個沒有
...
COUNT(CASE WHEN overtime = 'No' THEN 1 END) as yes,
...
而已。 case
表達式將匹配的行映射為1,同時將非映射行映射為null
(由於隱含else null
子句)。
只需添加四分之一列即可。
有關此技術的更多信息: http : //modern-sql.com/use-case/pivot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.