场景描述:办案方式、处置情况、办理结果分别为一个字段,下边的分支分别对应字段的不同值。
现需要统计每个字段不同值的数量,没有的需要填0,存在的进行累加。
select
CASE_INFO.CITY_CODE ,"SUM"("DECODE"( "CASE_INFO"."CASE_AJLB", ' 01', 1,'02',1,'03',1,'04',1,'05',1,0)) as CASE_SHSEFB ,
"SUM"("DECODE"( "CASE_INFO"."CASE_AJLB", ' 1', 1,0)) as CASE_BHS ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BAFS", ' 0', 1,0)) as CASE_ZCZB ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BAFS", ' 1', 1,0)) as CASE_YDBL ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BAFS" , ' 2', 1,0)) as CASE_SDBL ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BAFS", ' 3', 1,0)) as CASE_QT ,
"SUM"("DECODE"( "CASE_INFO"."CASE_CZQK", '0', 1,0)) as CASE_DC ,
"SUM"("DECODE"( "CASE_INFO"."CASE_CZQK", '1', 1,0)) as CASE_HCZ ,
"SUM"("DECODE"( "CASE_INFO"."CASE_CZQK", '2', 1,0)) as CASE_CH ,
"SUM"("DECODE"( "CASE_INFO"."CASE_CZQK", '3', 1,0)) as CASE_LASC ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BLJG", '0', 1,0)) as CASE_CSCJ ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BLJG", '1', 1,0)) as CASE_CFCJ ,
"SUM"("DECODE"( "CASE_INFO"."CASE_BLJG" , '2', 1,0)) as CASE_YSGAJG
FROM CASE_INFO LEFT JOIN CLUE_INFO ON CASE_INFO.CLUE_ID = CLUE_INFO.CLUE_ID
WHERE CLUE_INFO.CLUE_SOURCE ='00' OR CLUE_INFO.CLUE_SOURCE ='01' OR CLUE_INFO.CLUE_SOURCE ='02' OR CLUE_INFO.CLUE_SOURCE ='03'
GROUP BY CASE_INFO.CITY_CODE
注:1.orcale数据库 2. decode函数的理解 (oracle);对于mysql实现可用case when 3.sum函数累加