oracle中pivot函数的用法以及add_months函数用法

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等其他表达式

 

 

add_months 函数主要是对日期函数进行操作,在数据查询的过程中进行日期的按月增加,其形式为:

add_months(date,int);其中第一个参数为日期,第二个为按月增加的幅度,例如:

add_months (sysdate,2):就是当前日期的两个月之后的时间。

如:表示2个月以后的时间:select add_months(sysdate,2) from dual;

表示2个月以前的时间,可以用下列语句

select add_months(sysdate,-2) from dual;

如果第一个参数即当前日期的地方是某一个指定的具体日期,则该日期需要使用to_date('20190101','yyyymmdd')进行转换,如下:

select * from tb_user where create_date_time>to_date('20190101','yyyymmdd')and create_date_time<tadd_months(to_date('20190101','yyyymmdd'),2);

 

posted @ 2022-08-24 16:02  Samuel-Leung  阅读(2761)  评论(0编辑  收藏  举报