[英]SQL grouping by quarter and year
I'm working on a project that is kinda interesting at least to me... Right now I have this code. 我正在从事一个至少对我来说很有趣的项目……现在我有了这段代码。 While this works, what I'd like to present is one row for all of 2016 and the quarters of 2017 broken out.
虽然这行得通,但我想介绍的是2016年全年和2017年第四季度的一行。
SELECT account_id,
quarter, revenue,
sum(case when quarter like '%2016' then revenue else 0 end) as rev2016
FROM prescreen
GROUP BY quarter
ORDER BY rev2016 desc ;
What I am seeing is 我看到的是
account_id . quarter . revenue . rev2016
1 Q4-2016 . 600 . 600
1 Q1-2016 500 . 500
1 Q2-2016 400 400
1 Q3-2016 350 . 350
1 Q1-2017 1000 . 0
1 Q2-2017 . 650 . 0
1 Q3-2017 890 . 0
The expected output that I'd like to see is more like 我希望看到的预期输出更像
account_id . rev2016 . Q1-2017 . Q2-2017 . Q3-2017
1 . 1850 . 1000 . 650 . 890
What else can I try to get to a one line result here? 在这里我还能尝试得到一行结果吗?
In MySQL, you normally pivot by doing conditional aggregation: 在MySQL中,通常通过进行条件聚合来实现:
SELECT account_id,
(case when quarter like '2016%' then revenue else 0 end) as rev_2016,
(case when quarter like 'Q1-2017' then revenue else 0 end) as rev_2017Q1,
. . .
FROM prescreen
GROUP BY account_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.