sql 复杂查询count case 与 sum case

示例:查询不同类型来源的总数,来源自定义:

select count(case when c.source in
                ('web_form','phone_service','mobile_form','web_service','mobile_service')
                then 1  else null end ) as 线上,
            count(case when c.source in
                ('friends','business','offline','direct_form','email','customer')
                then 1  else null end ) as 线下,
            count(case when c.source in
                ('ctrip','Fliggy','mafengwo')
                then 1  else null end ) as 平台,
            count(case when c.source in
                ('wechat_service','wechat_form')
                then 1  else null end ) as 自媒体
            from case c
            where c.status = 3 and c.isdel = 0

2.查询不同类型来源订单的成交总金额:

select sum(case when c.source in
                ('web_form','phone_service','mobile_form','web_service','mobile_service')
                then o.rmb_price  else null end ) as 线上,
            sum(case when c.source in
                ('friends','business','offline','direct_form','email','customer')
                then o.rmb_price  else null end ) as 线下,
            sum(case when c.source in
                ('ctrip','Fliggy','mafengwo')
                then o.rmb_price  else null end ) as 平台,
            sum(case when c.source in
                ('wechat_service','wechat_form')
                then o.rmb_price  else null end ) as 自媒体
            from case c left JOIN order o
                on c.case_id=o.case_id
            where c.status = 3 and c.isdel = 0
不算最优,但很管用。

猜你喜欢

转载自blog.csdn.net/key_artist/article/details/80987377