一条sql获取每个类别最新的一条记录

1.初始化数据

create  table  Products
(
   id int identity(1,1),
   name  nvarchar(100),
   categroy int,
   addtime datetime ,
)
insert into  
Products (name ,categroy,addtime)
values 
('手机',1,'2016-10-01 00:00:00.000'),
('笔记本',1,'2016-10-02 00:00:00.000'),
('照相机',1,'2016-10-03 00:00:00.000'),

('上衣',2,'2016-10-01 00:00:00.000'),
('短袖',2,'2016-10-02 00:00:00.000'),
('裤子',2,'2016-10-03 00:00:00.000')

2.示例:

--id是主键
select *From   Products A
where   id in (
 select top 1 id from  Products where categroy=A.categroy order by addtime desc
)
--id  不是主键
select *From  Products A
where  1>(
 select count(1) from  Products where  categroy=A.categroy and addtime>a.addtime
)

--row_number 
select *From 
(
 select row_number() over (partition by categroy order by addtime desc) rownum,*
 from Products
) A where rownum<2

--cross apply
select distinct B.* from  Products A
cross apply
(
  select  top 1 * From  Products where  categroy=A.categroy order by addtime desc
) B

 

posted @ 2016-10-15 20:26  sulin  阅读(2393)  评论(0编辑  收藏  举报