行转列,例子:统计各科各出院情况人数
with t as(
SELECT b.科室ID,a.患者ID,a.result FROM 患者信息表 a
where a.出院时间 >= to_date('2021-6-1 00:00:00','yyyy-MM-dd hh24:mi:ss')
and a.出院时间 <= to_date('2021-6-20 23:59:59','yyyy-MM-dd hh24:mi:ss')
)
SELECT 科室ID,sum(治愈) 治愈,sum(好转) 好转,sum(未愈) 未愈,sum(死亡) 死亡,sum(其他) 其他 FROM (
SELECT 科室ID, 0 治愈, 0 好转, 0 未愈, 0 死亡, 0 其他 FROM t group by 科室ID union all
SELECT 科室ID, sum(1), 0, 0, 0, 0 FROM t where result=1 group by 科室ID union all /*治愈*/
SELECT 科室ID, 0, sum(1), 0, 0, 0 FROM t where result=2 group by 科室ID union all /*好转*/
SELECT 科室ID, 0, 0, sum(1), 0, 0 FROM t where result=3 group by 科室ID union all /*未愈*/
SELECT 科室ID, 0, 0, 0, sum(1), 0 FROM t where result=4 group by 科室ID union all /*死亡*/
SELECT 科室ID, 0, 0, 0, 0, sum(1) FROM t where result=9 group by 科室ID /*其他*/
) group by 科室ID