34,593
社区成员
发帖
与我相关
我的任务
分享
with t1 as
(select max(id) as id_1,xh from table group by xh)
select * from table where exists (select 1 from t1 where table.id =t1.id_1 and table.xh=t1.xh)
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([ID] int,[序号] int,[时间] Date)
Insert #T
select 1,1,'2017-11-17' union all
select 2,1,'2017-11-17' union all
select 3,2,'2017-11-17' union all
select 4,2,'2017-11-17' union all
select 5,3,'2017-11-17' union all
select 6,3,'2017-11-17' union all
select 7,4,'2017-11-17' union all
select 8,5,'2017-11-17'
Go
--测试数据结束
;WITH ctea AS (
Select *,ROW_NUMBER()OVER(PARTITION BY 序号 ORDER BY ID ) AS num from #T
),cteb AS (
SELECT 序号,MAX(num) AS num FROM ctea WHERE num<>1 GROUP BY 序号
)
SELECT ID ,
ctea.序号 ,
时间
FROM cteb
JOIN ctea ON ctea.num = cteb.num
AND ctea.序号 = cteb.序号