现有一表,原始数据如下:
![技术分享图片](https://image.cha138.com/20210627/e1650dde42d54bcfa42953bffa63b734.jpg)
现在需要查询出如下结果(条件是:[80,~]优秀,[60,80)及格,[~,60)不及格):
![技术分享图片](https://image.cha138.com/20210627/3b4e5801552e41e686b0410825cbf92c.jpg)
先用UNPIVOT对原始表进行转换,列转行
select * from CB_SHANGCICB UNPIVOT (cj for kc in ("语文","数学","英语")) ,结果如下:
![技术分享图片](https://image.cha138.com/20210627/395577371c494cc1b2911913c82699f8.jpg)
再对cj进行区间匹配
with tt as (select * from score unpivot (cj for kc in ("语文","数学","英语")))
select kc,(case when cj>=80 then ‘优秀‘ when cj>=60 then ‘及格‘ else ‘不及格‘ end) cj from tt;
执行结果如下:
![技术分享图片](https://image.cha138.com/20210627/f009871604fb4e8cafd01282c2d870e9.jpg)
然后使用PIVOT进行列转行
select * from (
with tt as (select * from score unpivot (cj for kc in ("语文","数学","英语")))
select kc,(case when cj>=80 then ‘优秀‘ when cj>=60 then ‘及格‘ else ‘不及格‘ end) cj from tt
) PIVOT max(cj) for kc in (‘语文‘ as "语文",‘数学‘ as "数学",‘英语‘ as "英语") ,红色背景部分必须为聚合函数;