22,209
社区成员
发帖
与我相关
我的任务
分享
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 行受影响)
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
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
--> 测试数据: #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)
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