我想在表 a 中筛选这样的记录,该如何用SQL语句实现呢?
原表:
编号 支付时间 支付金额
GA 200701 100
GA 200702 200
GC 200101 100
GC 200301 100
GB 200101 50
得出结果集:选出编号中支付时间最大的记录
运行结果应该是:
GA 200702 200
GC 200301 100
GB 200101 50
原表:
编号 支付时间 支付金额
GA 200701 100
GA 200702 200
GC 200101 100
GC 200301 100
GB 200101 50
得出结果集:选出编号中支付时间最大的记录
运行结果应该是:
GA 200702 200
GC 200301 100
GB 200101 50
(编号 varchar(50),
支付时间 varchar(50),
支付金额 varchar(50)
)
insert into #temp
select 'GA','200701','100' union all select 'GA','200702','200' union all select 'GC','200101','100' union all select 'GC','200301','100' union all select 'GB','200101','50'
select * from #temp
select distinct 编号,支付时间,支付金额
from #temp t
where not exists(select 1 from #temp where 编号=t.编号 and 支付时间>t.支付时间)
----------------
GA 200702 200
GB 200101 50
GC 200301 100
--借用rookie_one(流氓会武术,谁都挡不住) 的數據create table #temp
(编号 varchar(50),
支付时间 varchar(50),
支付金额 varchar(50)
)
insert into #temp
select 'GA','200701','100' union all select 'GA','200702','200' union all select 'GC','200101','100' union all select 'GC','200301','100' union all select 'GB','200101','50'select
A.*
from
#temp A
Inner Join
(select 编号, Max(支付时间) As 支付时间 from #temp Group By 编号) B
On A.编号 = B.编号 And A.支付时间 = B.支付时间
Order By
A.编号Drop Table #temp
--Result
/*
编号 支付时间 支付金额
GA 200702 200
GB 200101 50
GC 200301 100
*/