27,579
社区成员
发帖
与我相关
我的任务
分享
写得快了点,更正下。呵呵
select id,type,data from (select *,row_number() over(partition by type order by id desc) as rn from tb ) t where rn in(1,2)
select * from (select *,row_number() over(partition by type order by id desc) as rn from tb ) t where rn in(1,2)
select * from tb a where id in (select max(id) from tb group by type )
select * from 表 a where (select count(id) from 表 where type=a.type and id>a.id)<2
declare @tb1 table
(
id int,
[type] int,
data char(1)
)
insert into @tb1
select 1,1,'a' union all
select 3,1,'c' union all
select 4,1,'d' union all
select 2,2,'b' union all
select 5,2,'e'
select [id],[type],[data] from (
select row_number() over(partition by [type] order by id desc,[type]) as px ,* from @tb1) t
where px<=2
/*
id type data
----------- ----------- ----
4 1 d
3 1 c
5 2 e
2 2 b
*/
create table #DD
(
id int identity(1,1),
type int,
data char(1)
)
insert #DD select 1,'a'
union all select 2,'b'
union all select 1,'c'
union all select 1,'d'
union all select 2,'e'
select * from #DD DD where not exists (select * from #DD where DD.type=type and dd.id<id)
DECLARE @t TABLE(id INT,type INT,date NVARCHAR(10))
INSERT INTO @t
SELECT 1,1,'a' UNION ALL
SELECT 2,2,'b' UNION ALL
SELECT 3,1,'c' UNION ALL
SELECT 4,1,'d' UNION ALL
SELECT 5,2,'e'
SELECT * FROM @t a WHERE NOT EXISTS(SELECT * FROM @t WHERE type=a.type AND id>a.id)
select a.*
from mm a right join (select max(id) id,type from mm group by type) b
on a.type=b.type and a.id=b.id
declare @t table
(
id int identity(1,1),
type int,
data char(1)
)
insert @t select 1,'a'
union all select 2,'b'
union all select 1,'c'
union all select 1,'d'
union all select 2,'e'
select * from @t where id in( select max(ID) from @t group by type)
declare @tb1 table
(
id int,
[type] int,
data char(1)
)
insert into @tb1
select 1,1,'a' union all
select 3,1,'c' union all
select 4,1,'d' union all
select 2,2,'b' union all
select 5,2,'e'
select
id,
[type],
data
from @tb1 as t1
where not exists
(
select 1
from @tb1 as t2
where t2.[type]= t1.[type] and t1.id < t2.id
)
结果:
id type data
------------
4 1 d
5 2 e
思路:
1)先确定在相同的type下进行比较,既t2.[type]= t1.[type]的条件。
2)相同的type下,不存在该当id小于任何id的情况(既最大的id才不小于相同type下任意id,因为它等于最大的id)的数据被选出来。条件 not exists...t1.id < t2.id