关闭

求记录中的最新数据的方法!

1061人阅读 评论(3) 收藏 举报

已知数据:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:359095次
    • 积分:4652
    • 等级:
    • 排名:第6652名
    • 原创:104篇
    • 转载:2篇
    • 译文:2篇
    • 评论:103条
    最新评论
    朋友网站链接