日期:2014-05-18 浏览次数:20799 次
select spbh ,dwbh, max(rq)rq from tb group by spbh,dwbh
------解决方案--------------------
--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
create table [tbl]([spbh] varchar(5),[dwbh] varchar(1),[rq] datetime)
insert [tbl]
select 'spid1','A','2012-04-01' union all
select 'spid1','A','2012-03-01' union all
select 'spid1','B','2012-03-01' union all
select 'spid2','A','2012-04-01' union all
select 'spid2','B','2012-03-01' union all
select 'spid2','B','2012-02-01' union all
select 'spid3','A','2012-03-01' union all
select 'spid3','A','2012-02-01'
--2005以上
select [spbh],[dwbh],[rq] from(
select row=ROW_NUMBER()over(partition by [spbh],[dwbh] order by [rq] desc),
* from tbl)a
where row=1
--2000
--1
select * from tbl a
where [rq]=(select MAX([rq]) from tbl b where a.spbh=b.spbh and a.dwbh=b.dwbh)
order by [spbh],[dwbh]
--2
select spbh ,dwbh, max(rq)rq from tbl group by spbh,dwbh
--情况简单选择2就好了,复杂了使用1或者2005以上版本使用row_number
/*
spbh dwbh rq
spid1 A 2012-04-01 00:00:00.000
spid1 B 2012-03-01 00:00:00.000
spid2 A 2012-04-01 00:00:00.000
spid2 B 2012-03-01 00:00:00.000
spid3 A 2012-03-01 00:00:00.000
*/