需求:
1.Oracle中有如下表
CREATE TABLE TG_QMS.TEST
(
DATA1 VARCHAR2(20),
DATA2 VARCHAR2(20),
DATA3 VARCHAR2(20),
DATA4 NUMBER(3,0),
DATA5 NUMBER(3,0),
DATA6 VARCHAR2(1) NOT NULL
)
PCTFREE 10
MAXTRANS 255
TABLESPACE TGHIS10
STORAGE(INITIAL 64K MINEXTENTS 1 MAXEXTENTS 2147483645 BUFFER_POOL DEFAULT)
NOCACHE
LOGGING
2.其中数据如下:
N01010101 2013-08-06 10:30:30 贾翠兰 1 15 1
N01010101 2013-01-01 10:00:00 李四 2 20 2
N01010102 2013-08-06 10:30:30 贾翠兰 3 33 3
3.通过一个sql得到如下结果:
就是按单据分组 数量和金额累加
时间和审核人 取当前组中人任意一条即可
N01010101 贾翠兰 2013-08-06 10:30:30 1 35 3
N01010102 贾翠兰 2013-08-06 10:30:30 1 33 3
解决方法:
如果
时间和审核人可以不位于一条记录,可以直接用
select data1,max(data2),max(data3),sum(data4),sum(data5) from test group by data1;
如果要求时间和审核人需要位于同一组的同一条记录上则有三种方法 oracle分析函数有用啦
第一
select * from
( select data1,data2,data3,
SUM(data5) OVER( PARTITION by data1 ORDER BY data2 desc) sumje ,
SUM(data4) OVER( PARTITION by data1 ORDER BY data2 desc) sumtot,
ROW_NUMBER() OVER ( PARTITION by data1 ORDER BY data2 ASC) AS XH
from test )
WHERE XH = 1;
第二
select * from
(select data1 ,data3,data2,
row_number() over(partition by data1 order by data1) as sno ,
sum(data5) over (partition by data1) as sumje,
sum(data4) over (partition by data1) as sumtot
from test) a
where a.sno=1;
第三
select * from
(select data1 ,data3,data2,row_number() over(partition by data1 order by data1) as sno from test) a,
(select data1 ,sum(data5) as sumje,sum(data4) as sumtot from test group by data1) b
where a.sno=1
and a.data1=b.data1;
阅读(1681) | 评论(0) | 转发(0) |