日期:2014-05-16 浏览次数:20488 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-20 16:30:54
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([Id] int,[Name] varchar(3),[Result] int,[Date] datetime)
insert [huang]
select 1,'001',90,'2013-11-10' union all
select 2,'002',85,'2013-11-10' union all
select 3,'003',87,'2013-11-10' union all
select 4,'001',95,'2013-11-15' union all
select 5,'002',83,'2013-11-15' union all
select 6,'003',89,'2013-11-15' union all
select 7,'001',92,'2013-11-20' union ALL
select 8,'002',83,'2013-11-20' union all
select 9,'003',88,'2013-11-20'
--------------开始查询--------------------------
select * from [huang]
DECLARE @n INT
SET @n=1
;with t
as(
select
px=ROW_NUMBER()over(partition by name order by [date] desc),
*
from [huang]
)
select
name,[date],Result from t a
where exists(select 1 from t b where a.name=b.name and a.px=b.px-@n and a.Result>b.Result)
and px=1
----------------结果----------------------------
/*
*/