sum - case when

select 
 channel
 ,SUBSTR(paid_date,1,7) AS YYMM
 ,SUM(orders) AS sum_orders
from report_daily_sales_by_channel_by_store
where paid_date >= '2019-10-01'                            
and   paid_date <  '2020-01-01' 
group by channel, SUBSTR(paid_date,1,7)
;
+----------+----------+-------------+
| channel  |   yymm   | sum_orders  |
+----------+----------+-------------+
| SNG      | 2019-10  | 21154085    |
| SNG      | 2019-11  | 20433075    |
| SNG      | 2019-12  | 21052846    |
| WMDJ     | 2019-10  | 1803969     |
| WMDJ     | 2019-11  | 1833128     |
| WMDJ     | 2019-12  | 972400      |
| JDDJ     | 2019-10  | 3229328     |
| JDDJ     | 2019-11  | 3015826     |
| JDDJ     | 2019-12  | 2975539     |
| WFS      | 2019-10  | 414686      |
| WFS      | 2019-11  | 596486      |
| WFS      | 2019-12  | 410759      |
| OFFLINE  | 2019-10  | 25583525    |
| OFFLINE  | 2019-11  | 22955407    |
| OFFLINE  | 2019-12  | 23555036    |
+----------+----------+-------------+

 

select 
 YYMM
 ,sum(case when channel='SNG'     then sum_orders else 0 end)   AS SNG_orders
 ,sum(case when channel='WMDJ'    then sum_orders else 0 end)   AS WMDJ_orders
 ,sum(case when channel='JDDJ'    then sum_orders else 0 end)   AS JDDJ_orders
 ,sum(case when channel='WFS'     then sum_orders else 0 end)   AS WFS_orders
 ,sum(case when channel='OFFLINE' then sum_orders else 0 end)   AS OFFLINE_orders
from ( 
--1
select channel ,SUBSTR(paid_date,1,7) AS YYMM ,SUM(orders) AS sum_orders from report_daily_sales_by_channel_by_store where paid_date >= '2019-10-01' and paid_date < '2020-01-01' group by channel, SUBSTR(paid_date,1,7) --end1
)
AS a group by YYMM order by YYMM ; +----------+-------------+--------------+--------------+-------------+-----------------+ | yymm | sng_orders | wmdj_orders | jddj_orders | wfs_orders | offline_orders | +----------+-------------+--------------+--------------+-------------+-----------------+ | 2019-10 | 21154085 | 1803969 | 3229328 | 414686 | 25583525 | | 2019-11 | 20433075 | 1833128 | 3015826 | 596486 | 22955407 | | 2019-12 | 21052846 | 972400 | 2975539 | 410759 | 23555036 | +----------+-------------+--------------+--------------+-------------+-----------------+

 

posted @ 2020-04-14 00:00  茗::流  阅读(390)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。