11月4号的随笔

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

已知数据:

Column1    Column2     Column3    Column4
A                      10                     am         1999-01-01 00:00:00.000
A                      11                     am         1999-01-02 00:00:00.000
B                     12                      bm         1999-01-03 00:00:00.000
B                     13                      bm         1999-01-04 00:00:00.000
C                    14                      cm         1999-01-05 00:00:00.000
C                     15                     cm         1999-01-06 00:00:00.000

要求得到数据:

Column1    Column2     Column3    Column4
A                      11                     am         1999-01-02 00:00:00.000
B                     13                      bm         1999-01-04 00:00:00.000
C                     15                     cm         1999-01-06 00:00:00.000

--数据装载

Create Table #T(Column1 varchar(10),Column2 int,Column3 varchar(10),Column4 datetime)
insert #T select 'A',10,'am','1999-1-1'
union all select 'A',11,'am','1999-1-2'
union all select 'B',12,'bm','1999-1-3'
union all select 'B',13,'bm','1999-1-4'
union all select 'C',14,'cm','1999-1-5'
union all select 'C',15,'cm','1999-1-6'

--测试语句 方法1:

select a.* from #T a
where (a.Column4) =
   (select top 1 (Column4) from #T where Column1 = a.Column1 order by Column4 desc)

--测试结果:

Column1    Column2     Column3    Column4                                               
---------- ----------- ---------- ------------------------------------------------------
A          11          am         1999-01-02 00:00:00.000
B          13          bm         1999-01-04 00:00:00.000
C          15          cm         1999-01-06 00:00:00.000

--测试语句 方法2:(最佳效率)

select a.* from #T a join(
 select Column1,Column4=max(Column4) from #T group by Column1
)b on a.Column1=b.Column1 and a.Column4=b.Column4
order by a.Column1

--测试结果 方法2:

Column1    Column2     Column3    Column4                                               
---------- ----------- ---------- ------------------------------------------------------
A          11          am         1999-01-02 00:00:00.000
B          13          bm         1999-01-04 00:00:00.000
C          15          cm         1999-01-06 00:00:00.000

posted on 2005-12-05 10:56  潘伟  阅读(194)  评论(0编辑  收藏  举报