62,046
社区成员
发帖
与我相关
我的任务
分享
select * from table2 a where not exists(select 1 from table2 where a.table1Id = table1Id and id>a.id )
select * from tb2 where id in(select distinct MAX(id) id from tb2 group by table1Id)
CREATE TABLE TABLE2(id int,UserName nvarchar(20),table1Id int)
INSERT INTO TABLE2 SELECT 1,'user1',1 UNION ALL
SELECT 2,'user2',1 UNION ALL
SELECT 3,'user3',2
SELECT [t3].[id] AS [Id], [t3].[UserName], [t3].[table1Id] AS [Table1Id]
FROM (
SELECT [t0].[table1Id]
FROM [TABLE2] AS [t0]
GROUP BY [t0].[table1Id]
) AS [t1]
OUTER APPLY (
SELECT TOP (1) 1 AS [test], [t2].[id], [t2].[UserName], [t2].[table1Id]
FROM [TABLE2] AS [t2]
WHERE (([t1].[table1Id] IS NULL) AND ([t2].[table1Id] IS NULL)) OR (([t1].[table1Id] IS NOT NULL) AND ([t2].[table1Id] IS NOT NULL) AND ([t1].[table1Id] = [t2].[table1Id]))
ORDER BY [t2].[id] DESC
) AS [t3]
ORDER BY [t3].[id]
DROP TABLE TABLE2
Id UserName Table1Id
----------- -------------------- -----------
2 user2 1
3 user3 2