欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL 分组后只获取每组的一条数据

程序员文章站 2022-11-08 10:46:27
/****** Object: Table [dbo].[TEMP] Script Date: 2018-8-22 星期三 23:33:09 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[TE... ......
/****** object:  table [dbo].[temp]    script date: 2018-8-22 星期三 23:33:09 ******/
set ansi_nulls on
go
set quoted_identifier on
go
create table [dbo].[temp](
	[id] [nvarchar](36) null,
	[serialno] [nvarchar](36) null,
	[qty] [numeric](10, 1) null,
	[foreignid] [nvarchar](32) null,
	[flag] [bit] not null,
	[createdate] [datetime] not null
) on [primary]

go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'6073188b18574593b847dd0cac936dd5', n'1bf1c0f4f5034b2588b1c2e2b4f80294', cast(10.0 as numeric(10, 1)), n'f6df43bdc3ef4eaeb8c0d98c9abea7eb', 0, cast(0x0000a944017bbfef as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'6073188b18574593b847dd0cac936dd5', n'1bf1c0f4f5034b2588b1c2e2b4f80294', cast(10.0 as numeric(10, 1)), n'b01892f11a284eea990afe0a4e4398b4', 0, cast(0x0000a944017bdef9 as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'136eba69477c41879e4d0cf9a791d460', n'e60cffd61c314d248403cfd08370ed8c', cast(10.0 as numeric(10, 1)), n'4ca2da2abf434910b5d3d6ed6c343637', 0, cast(0x0000a944017c3f82 as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'136eba69477c41879e4d0cf9a791d460', n'e60cffd61c314d248403cfd08370ed8c', cast(10.0 as numeric(10, 1)), n'b6fa2439e5bb44c58cff03b2725558d8', 0, cast(0x0000a944017c5604 as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'136eba69477c41879e4d0cf9a791d460', n'e60cffd61c314d248403cfd08370ed8c', cast(11.0 as numeric(10, 1)), n'c465a72d36b5450e9a53e565ed95012d', 1, cast(0x0000a944017b4ec2 as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'136eba69477c41879e4d0cf9a791d460', n'e60cffd61c314d248403cfd08370ed8c', cast(20.0 as numeric(10, 1)), n'd68efcd219634579966801b036ca8e29', 1, cast(0x0000a944017c7370 as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'6073188b18574593b847dd0cac936dd5', n'1bf1c0f4f5034b2588b1c2e2b4f80294', cast(8.0 as numeric(10, 1)), n'2178fc8b537e4841a505e5e5a960ed83', 1, cast(0x0000a944017c94cd as datetime))
go
insert [dbo].[temp] ([id], [serialno], [qty], [foreignid], [flag], [createdate]) values (n'6073188b18574593b847dd0cac936dd5', n'1bf1c0f4f5034b2588b1c2e2b4f80294', cast(22.0 as numeric(10, 1)), n'7306f311b69e425cba13991030d7a2d3', 1, cast(0x0000a944017cb571 as datetime))
go
select * from dbo.temp a
where a.foreignid in (
	select top 1 b.foreignid from dbo.temp b where b.id = a.id and b.serialno = a.serialno
	order by b.flag,b.createdate
)