1 a aa 20 2013/5/1 0:00 e 2344 0
1 a aa 30 2013/5/2 0:00 e 1234 1
2 b bb 85 2013/5/3 0:00 r 2341 0
2 b bb 11 2013/5/4 0:00 j 3244 2
3 c cc 3 2013/5/5 0:00 r 3423 2
3 c cc 30 2013/5/6 0:00 g 1223 3
4 d dd 48 2013/5/7 0:00 j 2134 1
如上图所示,根据件号、供应商汇总数量,然后时间、使用者、批号、备注显示为时间最近的记录。
结果如下图所示:
件号 名称 供应商 数量 时间 使用者 批号 备注
1 a aa 30 2013/5/2 0:00 e 1234 1
2 b bb 11 2013/5/4 0:00 j 3244 2
3 c cc 30 2013/5/6 0:00 g 1223 3
4 d dd 48 2013/5/7 0:00 j 2134 1
请高手指点,用SQL语句实现。
6 个解决方案
#1
select * from
(select t.*,row_number() over(partition by 件号 order by 时间 desc ) rn from t) t
where t.rn=1
(select t.*,row_number() over(partition by 件号 order by 时间 desc ) rn from t) t
where t.rn=1
#2
with t1 as
(
select 1 c1,'a' c2,'aa' c3,20 c4,'2013-05-01' c5,2222 c6 from dual union all
select 1 c1,'a' c2,'aa' c3,30 c4,'2013-05-02' c5,1111 c6 from dual union all
select 2 c1,'b' c2,'bb' c3,85 c4,'2013-05-03' c5,3333 c6 from dual union all
select 2 c1,'b' c2,'bb' c3,11 c4,'2013-05-04' c5,4444 c6 from dual
)
select c1,c2,c3,c4,c5,c6
from
(
select c1,c2,c3,c4,c5,c6,row_number() over(partition by c1 order by c5 desc) rn
from t1
)
where rn = 1
c1 c2 c3 c4 c5 c6
----------------------------------------------------------------
1 1 a aa 30 2013-05-02 1111
2 2 b bb 11 2013-05-04 4444
#3
select t1.*
from t1,(select c1,max(c5) c5
from t1
group by c1) t2
where t1.c1 = t2.c1 and t1.c5 = t2.c5
order by t1.c1
#4
推荐使用row_number() over()
#5
#6
u010412956的回答,及时解决了我的问题,谢谢
#1
select * from
(select t.*,row_number() over(partition by 件号 order by 时间 desc ) rn from t) t
where t.rn=1
(select t.*,row_number() over(partition by 件号 order by 时间 desc ) rn from t) t
where t.rn=1
#2
with t1 as
(
select 1 c1,'a' c2,'aa' c3,20 c4,'2013-05-01' c5,2222 c6 from dual union all
select 1 c1,'a' c2,'aa' c3,30 c4,'2013-05-02' c5,1111 c6 from dual union all
select 2 c1,'b' c2,'bb' c3,85 c4,'2013-05-03' c5,3333 c6 from dual union all
select 2 c1,'b' c2,'bb' c3,11 c4,'2013-05-04' c5,4444 c6 from dual
)
select c1,c2,c3,c4,c5,c6
from
(
select c1,c2,c3,c4,c5,c6,row_number() over(partition by c1 order by c5 desc) rn
from t1
)
where rn = 1
c1 c2 c3 c4 c5 c6
----------------------------------------------------------------
1 1 a aa 30 2013-05-02 1111
2 2 b bb 11 2013-05-04 4444
#3
select t1.*
from t1,(select c1,max(c5) c5
from t1
group by c1) t2
where t1.c1 = t2.c1 and t1.c5 = t2.c5
order by t1.c1
#4
推荐使用row_number() over()
#5
#6
u010412956的回答,及时解决了我的问题,谢谢