Split column conditionally

时间:2016-07-11 19:15:06

标签: mysql sql

I want to split a column based on if a condition is true or false and count the number of patients in each category for each doctor

This is my code:

SELECT p.MRP_CP_ID, COUNT(p.PTNT_ID) FROM PATIENT p
JOIN PATIENT_SCHEDULE ps ON ps.PTNT_ID = p.PTNT_ID
WHERE ps.MLTPL_PHRM_FLG = 0
GROUP BY MRP_CP_ID;

But i want to display the count of patients for where the MLTPL_PHRM_FLG is 1 in another column. Is there an easy way to do this?

current result from that displayed here

1 个答案:

答案 0 :(得分:0)

This can be done with conditional aggregation.

SELECT p.MRP_CP_ID, 
COUNT(*) Total,
COUNT(CASE WHEN ps.MLTPL_PHRM_FLG = 0 then 1 END) as PHRM_FLG_0_Counts,
COUNT(CASE WHEN ps.MLTPL_PHRM_FLG = 1 then 1 END) as PHRM_FLG_1_Counts
FROM PATIENT p
JOIN PATIENT_SCHEDULE ps ON ps.PTNT_ID = p.PTNT_ID
GROUP BY MRP_CP_ID;