日期:2014-05-16 浏览次数:20567 次
select * from tb t where not exists(select 1 from tb where id=t.id and time>t.time)
----------------------------------------------------------------
-- Author :DBA_HuangZJ(发粪涂墙)
-- Date :2014-04-02 11:50:53
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)
-- Apr 2 2010 15:48:46
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[IDP] nvarchar(2),[TIME] datetime)
insert [huang]
select 1,'A','2014-03-15' union all
select 1,'B','2014-03-16' union all
select 2,'A','2014-03-12' union all
select 2,'C','2014-03-25' union all
select 3,'B','2014-03-01'
--------------生成数据--------------------------
SELECT *
FROM huang a
WHERE EXISTS (SELECT 1 FROM (
select Id,MAX([time])[TIME]
from [huang]
GROUP BY id)b WHERE a.id=b.id AND a.[time]=b.[time])
----------------结果----------------------------
/*
ID IDP TIME
----------- ---- -----------------------
1 B 2014-03-16 00:00:00.000
2 C 2014-03-25 00:00:00.000
3 B 2014-03-01 00:00:00.000
*/
select id,id