数据源:
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘1‘, N‘HEX_1‘, N‘张三‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘2‘, N‘HEX_2‘, N‘lisi‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘3‘, N‘HEX_3‘, N‘wangwu‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘4‘, N‘HEX_1‘, N‘zhangsan‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘5‘, N‘HEX_2‘, N‘里斯‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘6‘, N‘HEX_3‘, N‘王五‘)
GO
GO
INSERT INTO [dbo].[dept] ([id], [code], [name]) VALUES (N‘7‘, N‘HEX_3‘, N‘def‘)
业务:根据code 分组然后取出每组中的任意一行
SELECT *from(
SELECT
*, row_number () OVER (
partition BY code
ORDER BY
code DESC
) rowid
FROM
dept
) t
WHERE
rowid = 1;
使用 partition BY : 对多行数据分组后排序取每个产品的第一行数据
得到结果: