转自:http://www.linuxidc.com/Linux/2012-06/62894.htm
需求:统计WAIT_ORDER表中的工单总数、未处理工单总数、已完成工单总数、未完成工单总数。
表结构 : 为了举例子方便,WAIT_ORDER表只有两个字段,分别是ID、STATUS,其中STATUS为工单的状态。1表示未处理,2表示已完成,3表示未完成总数。
SQL:
结果为下图:

下半部分,来自工作中:
原SQL:
SELECT A.app_cnt
,COALESCE(B.m_active_app_cnt,0)
,COALESCE(D.accu_cust_cnt,0)
,COALESCE(B.m_active_cust_cnt,0)
,COALESCE(C.m_launch_cust_cnt,0)
FROM (
SELECT '2015-09-23' as etl_date,
count(1) as app_cnt
FROM s_sdk_add_new_app
) A
left outer join
(SELECT '2015-09-23' as etl_date
,count(1) as m_active_app_cnt
,sum(index_value) as m_active_cust_cnt
FROM a_sdk_rest_base
WHERE parti_dt ='2015-09-23'
and parti_index ='10002'
and frequency_cd ='01'
and condition_id ='10000000000000'
and index_value > 0
) B
ON A.etl_date = B.etl_date
left outer join
(SELECT '2015-09-23' as etl_date
,count(1) as m_active_app_cnt
,sum(index_value) as m_launch_cust_cnt
FROM a_sdk_rest_base
WHERE parti_dt ='2015-09-23'
and parti_index ='10004'
and frequency_cd ='01'
and condition_id ='10000000000000'
) C
ON A.etl_date = C.etl_date
left outer join
(SELECT '2015-09-23' as etl_date
,sum(index_value) as accu_cust_cnt
FROM a_sdk_rest_base
WHERE parti_dt ='2015-09-23'
and parti_index ='10006'
and frequency_cd ='01'
and condition_id ='10000000000000'
) D
ON A.etl_date = D.etl_date
修改后的SQL:
SELECT A.app_cnt
,COALESCE(B.m_active_app_cnt,0)
,COALESCE(B.accu_cust_cnt,0)
,COALESCE(B.m_active_cust_cnt,0)
,COALESCE(B.m_launch_cust_cnt,0)
FROM (
SELECT '2015-09-23' as etl_date,
count(1) as app_cnt
FROM s_sdk_add_new_app
) A
left outer join
(
SELECT
'2015-09-23' as etl_date
,count((case when parti_index = '10002' then 1 end)) m_active_app_cnt
,sum((case when parti_index ='10006' then index_value else 0 end )) accu_cust_cnt
,sum((case when parti_index ='10002' then index_value else 0 end )) m_active_cust_cnt
,sum((case when parti_index ='10004' then index_value else 0 end )) m_launch_cust_cnt
FROM a_sdk_rest_base
WHERE
parti_dt ='2015-09-23'
and parti_index in ('10006','10004','10002')
and frequency_cd ='01'
and condition_id ='10000000000000'
and index_value > 0
) B
ON A.etl_date = B.etl_date
16 3 4437 4437 0
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22569416/viewspace-1973856/ ,如需转载,请注明出处,否则将追究法律责任。