22,209
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE [dbo].[testDT](
[bh] [varchar](50) NULL,
[name] [varchar](50) NULL,
[sex] [int] NULL,
[email] [varchar](50) NULL
)
--sql 2005
select bh , name , sex , email from
(
select t.* , row_number() over(partition by bh order by name , sex , email) px from testdt t
) m
where px = 1
--sql 2000,如果某个字段能根据bh区分大小,例如email
select t.* from testdt t where email = (select min(email) from testdt where bh = t.bh)
select t.* from testdt t where not exists (select 1 from testdt where bh = t.bh and email < t.email)
--如果没有任何一个(多个)字段能根据bh区分大小。则需要使用临时表
select t.* , px = identity(int,1,1) into tmp from testdt t
select t.bh , t.name , t.sex , t.email from tmp t where px = (select min(px) from tmp where bh = t.bh)
select t.bh , t.name , t.sex , t.email from tmp t where not exists (select 1 from tmp where bh = t.bh and px < t.px)
select [bh],min(name) name,min(sex) sex,min(email) email from [testDT]
group by [bh]