现有一表,原始数据如下:
现在需要查询出如下结果(条件是:[80,~]优秀,[60,80)及格,[~,60)不及格):
先用UNPIVOT对原始表进行转换,列转行
select * from CB_SHANGCICB UNPIVOT (cj for kc in ("语文","数学","英语")) ,结果如下:
再对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;
执行结果如下:
然后使用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 "英语") ,红色背景部分必须为聚合函数;
原文地址:https://www.cnblogs.com/zzwo/p/8624409.html
时间: 2024-10-03 06:33:14