pivot函数:对查询结果行转列进行统计
示例:
比如我想查每个用户投资的各种类型基金的分别有多少份额
平常的写法:
select userID,fundtype,sum(shares) from userasset group by userID,fundtype;
这样展示,如果行数很多的话,就很不直观,我看不出来某个基金哪个人投资最多,要看某个人投资的某个基金份额数,也要对照着fundtype去找。就很不方便。
我想一个人展示成一行,这样就好看多了
可以这样写
select userID, sum(decode(fundtype,'11',shares,0)) type11, sum(decode(fundtype,'12',shares,0)) type12, sum(decode(fundtype,'13',shares,0)) type13, sum(decode(fundtype,'14',shares,0)) type14, from userasset group by userID,fundtype;
也可以这样写
select userID, sum(case fundtype when '11' then shares else 0 end) type11, sum(case fundtype when '12' then shares else 0 end) type12, sum(case fundtype when '13' then shares else 0 end) type13, sum(case fundtype when '14' then shares else 0 end) type14 from userasset group by userID,fundtype;
效果是一样的:
pivot
的写法如下:
select * from (select userID, fundtype, shares from userasset ) t pivot(sum(shares) for fundtype in('11' type11,'12' type12,'13' type13,'14' type14 ));
效果跟上图一致。复杂查询的时候写法相比就会显得简单一点。
pivot里除了可以sum 也可以avg min max等其他表达式
标签:fundtype,sum,userID,shares,用法,oracle,pivot,select From: https://www.cnblogs.com/Samuel-Leung/p/16620403.html