1. 程式人生 > >關於case when複雜sql語句查詢

關於case when複雜sql語句查詢

問題描述:
需要查詢出學生在不同流程狀態對應的活動個數,流程狀態分為五個狀態audit、havePass、notPass、reject、giveup;活動有社會活動(xg_credit_comm_activity_apply)、比賽活動(xg_credit_innov_match_apply)、培訓活動(xg_credit_innov_train_apply)。

需要得到的效果:
這裡寫圖片描述

SQL拼接步驟:
Step1: 統計學生在所有活動中不同流程狀態對應的活動個數

SELECT student_id,`status`,COUNT(*) as counts from (
  SELECT
student_id, `status` from xg_credit_comm_activity_apply UNION ALL SELECT student_id, `status` from xg_credit_innov_match_apply UNION ALL SELECT student_id,`status` from xg_credit_innov_train_apply )as t GROUP BY t.student_id, t.`status`

這裡寫圖片描述

Step2:

SELECT t1.student_id as stuId,
CASE
when t1.`status`='AUDIT' then t1.counts ELSE 0 END as audit, CASE when t1.`status`='HAVEPASS' then t1.counts ELSE 0 END as havePass, CASE when t1.`status`='NOTPASS' then t1.counts else 0 END as notPass, CASE when t1.`status`='REJECT' then t1.counts else 0 END as reject, CASE when t1.`status`='GIVEUP' then
t1.counts else 0 END as giveup from ( SELECT student_id,`status`,COUNT(*) as counts from ( SELECT student_id, `status` from xg_credit_comm_activity_apply UNION ALL SELECT student_id, `status` from xg_credit_innov_match_apply UNION ALL SELECT student_id,`status` from xg_credit_innov_train_apply )as t GROUP BY t.student_id, t.`status` )as t1

這裡寫圖片描述

Step3:

SELECT stuId, SUM(audit) as audit,SUM(havePass) as havePass, SUM(notPass) as notPass, SUM(reject) as reject, SUM(giveup) as giveup from (

SELECT t1.student_id as stuId,
CASE when t1.`status`='AUDIT' then t1.counts ELSE 0 END as audit,
CASE when t1.`status`='HAVEPASS' then t1.counts ELSE 0 END as havePass,
CASE when t1.`status`='NOTPASS' then t1.counts else 0 END as notPass,
CASE when t1.`status`='REJECT' then t1.counts else 0 END as reject,
CASE when t1.`status`='GIVEUP' then t1.counts else 0 END as giveup
 from (

SELECT student_id,`status`,COUNT(*) as counts from (

SELECT student_id, `status`  from xg_credit_comm_activity_apply 
UNION ALL
SELECT student_id, `status` from xg_credit_innov_match_apply 
UNION ALL
SELECT student_id,`status` from xg_credit_innov_train_apply 

 )as t GROUP BY t.student_id, t.`status`

)as t1

)as  t2 GROUP BY t2.stuId

這裡寫圖片描述