22,210
社区成员
发帖
与我相关
我的任务
分享
if not object_id(N'Tempdb..#tab') is null
drop table #tab
Go
Create table #tab(DJBH nvarchar(23),SPDM nvarchar(22),RQ Date,SL int)
Insert #tab
select N'001',N'S1','2016-01-01',23 union all
select N'001',N'S1','2016-01-02',14 union all
select N'001',N'S2','2016-01-01',45 union all
select N'002',N'S1','2016-01-01',1 union all
select N'002',N'S3','2016-02-09',0 union all
select N'002',N'S3','2016-07-12',90 union all
select N'003',N'S2','2017-03-01',11 union all
select N'003',N'S4','2016-07-11',13 union all
select N'003',N'S4','2016-08-01',14
Select *
From #tab a
Where RQ=(Select min(rq) From #tab where SPDM=a.SPDM and djbh=a.DJBH)
select
*
from
(
select row_number() over(partition by djbh,spdm order by rq) as rid,*
) as t
where t.rid=1
use Tempdb
go
--> --> 听雨停了-->测试数据
if not object_id(N'Tempdb..#tab') is null
drop table #tab
Go
Create table #tab(DJBH nvarchar(23),SPDM nvarchar(22),RQ Date,SL int)
Insert #tab
select N'001',N'S1','2016-01-01',23 union all
select N'001',N'S1','2016-01-02',14 union all
select N'001',N'S2','2016-01-01',45 union all
select N'002',N'S1','2016-01-01',1 union all
select N'002',N'S3','2016-02-09',0 union all
select N'002',N'S3','2016-07-12',90 union all
select N'003',N'S2','2017-03-01',11 union all
select N'003',N'S4','2016-07-11',13 union all
select N'003',N'S4','2016-08-01',14
--测试数据结束
;WITH cte AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY djbh, spdm ORDER BY rq) AS rn
FROM #tab
)
SELECT DJBH,
SPDM,
RQ,
SL
FROM cte
WHERE rn = 1
ORDER BY DJBH,
SPDM