sql分组排序

我们有一张数据表,需要按照【类别】分组按照【时间】排序,并分组显示各自的序号。

表Archive

ArchiveId varchar(30) 文章编号非数字
CategoryId int 文章分类Id
StatusId int 状态,-1表示删除,0表示新建,1表示启用
PubTime DateTime 发布时间
select top 100 ArchiveId,StatusId,PubTime,CategoryId 
from Archive 
where StatusId>=0
order by PubTime desc

查询结果:

按照【类别】分组按照【时间】排序,并分组显示各自的序号。具体做法:
--子表
with asm as(select ArchiveId,StatusId,PubTime,CategoryId from Archive where StatusId>=0)

--查询-------------------
select bb.ArchiveId,bb.StatusId,bb.PubTime,bb.CategoryId,
--序号列生成
   (select COUNT(1) from asm where bb.CategoryId=asm.CategoryId and  bb.PubTime>=asm.PubTime) rowid 
--插入临时表
into #temp  

from Archive bb
where bb.StatusId>=0 

查询临时表:

select top 200 * from #temp  order by CategoryId desc,rowid asc

见查得结果:

原文地址:https://www.cnblogs.com/songshuai/p/3748016.html