日期:2014-05-18 浏览次数:20506 次
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
------解决方案--------------------
select * from tb2 where id in(select distinct MAX(id) id from tb2 group by table1Id)