100分求助 distinct + group by 续 在线等待

yqlx521 2011-02-18 12:18:07
在 sql server 2008 下 实现
select a,b,c,d,e from table
我现在想把 a,b着个字段 重复的去掉 要怎么做啊
想得到如下结果 a b c d e
1 2 3 4 5
2 2 3 4 6
1 2 5 7 9
3 4 6 7 8
1 3 5 9 8

查询后结果 2 2 3 4 6
3 4 6 7 8
1 3 5 9 8
1 2 3 4 5 和 1 2 5 7 9 拿出一条就行


...全文
98 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
AcHerat 2011-02-18
  • 打赏
  • 举报
回复

create table tb (a int,b int,c int,d int,e int)
insert into tb
select 1 ,2 ,3, 4, 5 union all
select 2 ,2 ,3, 4, 5 union all
select 1 ,2 ,5, 6, 7 union all
select 3 ,4 ,3, 4, 5 union all
select 1 ,3 ,5, 9, 8
go

with cte as
(
select rn = row_number() over (partition by a,b order by c),*
from tb
)
select a,b,c,d,e from cte where rn = 1

--or

select *
from tb a
where not exists (select 1 from tb where a = a.a and b = a.b and c > a.c)
order by a,b

drop table tb



a b c d e
----------- ----------- ----------- ----------- -----------
1 2 3 4 5
1 3 5 9 8
2 2 3 4 5
3 4 3 4 5

(4 行受影响)

a b c d e
----------- ----------- ----------- ----------- -----------
1 2 5 6 7
1 3 5 9 8
2 2 3 4 5
3 4 3 4 5

(4 行受影响)
快溜 2011-02-18
  • 打赏
  • 举报
回复

create table tb (a int,b int,c int,d int,e int)
insert into tb
select 1 ,2 ,3, 4, 5 union all
select 2 ,2 ,3, 4, 5 union all
select 1 ,2 ,5, 6, 7 union all
select 3 ,4 ,3, 4, 5 union all
select 1 ,3 ,5, 9, 8


with cte as
(
select row_number() over(partition by rtrim(a)+rtrim(b) order by c) as num,* from tb
)
select a,b,c,d,e from cte where num=1
/*
a b c d e
----------- ----------- ----------- ----------- -----------
1 2 3 4 5
1 3 5 9 8
2 2 3 4 5
3 4 3 4 5
guguda2008 2011-02-18
  • 打赏
  • 举报
回复
select a,b,c,d,e 
from (
SELECT *,ROW_NUMBER() OVER(PARTITION BY A,B ORDER BY C,D,E) AS NID
FROM [table]
) T WHERE NID=1
Xiao_Ai_Mei 2011-02-18
  • 打赏
  • 举报
回复
--> 测试数据: #tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (a int,b int,c int,d int,e int)
insert into #tb
select 1,2,3,4,5 union all
select 2,2,3,4,6 union all
select 1,2,5,7,9 union all
select 3,4,6,7,8 union all
select 1,3,5,9,8

select * from #tb t
where not exists(select * from #tb where a=t.a and b=t.b and e>t.e)


a b c d e
----------- ----------- ----------- ----------- -----------
2 2 3 4 6
1 2 5 7 9
3 4 6 7 8
1 3 5 9 8

(4 row(s) affected)
lds1ove 2011-02-18
  • 打赏
  • 举报
回复
打一壶酱油 2011-02-18
  • 打赏
  • 举报
回复
select a,b,c,d,e 
from (
SELECT *,ROW_NUMBER() OVER(PARTITION BY A,B ORDER BY C,D,E) AS NID
FROM [table]
) T WHERE NID=1

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧