现有如下的数据 需要统计三餐消费中哪一餐消费最高,思路是先进行列转行 再使用row_number() over()函数进行排名可以获取排名 再取pm=1的数据
xh | zcxfje(早餐) | wcxfje(中餐) | wacxfje(晚餐) |
1000 | 26975 | 126535 | 42310 |
1001 | 3490 | 85200 | 36780 |
语句实现如下:
with tmp_table as (
select xh, zczje as sczje,'早餐' as sclx from (
select xh,sum(zcxfje)as zczje,
sum(wcxfje)as wczje,sum(wacxfje)as waczje
from adm.edu_app_ykt_scxf
GROUP BY xh )as tab1
union all
select xh, wczje as sczje ,'午餐' as sclx from (
select xh,sum(zcxfje)as zczje,
sum(wcxfje)as wczje,sum(wacxfje)as waczje
from adm.edu_app_ykt_scxf
GROUP BY xh )as tab1
union all
select xh, waczje as sczje ,'晚餐' as sclx from (
select xh,sum(zcxfje)as zczje,
sum(wcxfje)as wczje,sum(wacxfje)as waczje
from adm.edu_app_ykt_scxf
GROUP BY xh )as tab1
)
select* from (select xh,row_number() over(partition by xh ORDER BY sczje desc ) as pm ,sczje,sclx
from tmp_table)as table1
where pm=1
先使用with 语句进行列转换成行 并补充三餐类型,再进行窗口排名函数即可得出结果。
暂时只想到该办法,有好的办法欢迎留言讨论。