SELECT chospital.hoscode as hospcode,chospital.hosname as hospname ,
count(DISTINCT CASE WHEN q_chronic.ht = ht
AND q_chronic.dm IS NULL THEN q_chronic.PID ELSE NULL END ) AS htonly ,
count(DISTINCT CASE WHEN q_chronic.dm = dm AND q_chronic.ht IS NULL THEN q_chronic.PID ELSE NULL END ) AS dmonly ,
count(DISTINCT CASE WHEN q_chronic.ht = ht AND q_chronic.dm =dm THEN q_chronic.PID ELSE NULL END ) AS htdm ,
count(DISTINCT CASE WHEN q_chronic.ht <> " " OR q_chronic.dm <> " " THEN q_chronic.PID ELSE NULL END ) AS total
FROM (SELECT chronic.PID,chronic.HOSPCODE,GROUP_CONCAT(chronic.CHRONIC) AS g_chronic,chronic.TYPEDISCH ,
MAX(CASE WHEN chronic.CHRONIC BETWEEN "I10" AND "I159" THEN "ht" ELSE NULL END ) AS ht ,
MAX(CASE WHEN chronic.CHRONIC BETWEEN "E10" AND "E149" THEN "dm" ELSE NULL END ) AS dm
FROM chronic GROUP BY concat(chronic.PID,chronic.HOSPCODE)
ORDER BY chronic.HOSPCODE ) AS q_chronic
INNER JOIN chospital ON chospital.hoscode=q_chronic.HOSPCODE
INNER JOIN person ON person.PID=q_chronic.PID
AND person.HOSPCODE=q_chronic.HOSPCODE
INNER JOIN campur on chospital.provcode = campur.changwatcode
AND chospital.distcode = ampurcode
WHERE
q_chronic.TYPEDISCH IN ("03") AND
person.TYPEAREA IN ("1","2")
and person.discharge = "9" and person.nation ="099"
GROUP BY chospital.hoscode