日期:2014-05-17 浏览次数:20534 次
if object_id('[T]') is not null drop table [T]
go
create table [T]([id] int,[AA] varchar(1),[BB] int)
insert [T]
select 1,'a',10 union all
select 2,'a',8 union all
select 3,'a',6 union all
select 4,'b',11 union all
select 5,'b',3 union all
select 6,'c',540 union all
select 7,'c',55
go
select * from t a
where not exists(select 1 from t where aa=a.aa and bb>a.bb)
/**
id AA BB
----------- ---- -----------
1 a 10
4 b 11
6 c 540
(3 行受影响)
**/
select * from t a
where not exists(select 1 from t where aa=a.aa and bb>a.bb)
select * from t a
where not exists(select 1 from t where aa=a.aa and (bb>a.bb or (bb=a.bb and id<t.id)))
--> 测试数据:#tb
IF OBJECT_ID('TEMPDB.DBO.#tb') IS NOT NULL DROP TABLE #tb
GO
CREATE TABLE #tb([id] INT,[AA] VARCHAR(1),[BB] INT)
INSERT #tb
SELECT 1,'a',10 UNION ALL
SELECT 2,'a',8 UNION ALL
SELECT 3,'a',6 UNION ALL
SELECT 4,'b',11 UNION ALL
SELECT 5,'b',3 UNION ALL
SELECT 6,'c',540 UNION ALL
SELECT 7,'c',55 UNION ALL
SELECT 8,'c',540