sqlserver 循环查询

在项目中。碰到一个问题。。

如下图。蓝色的如公务员、基础教育等属于一张表Category。小黑色的是从表TB_Classinfo中查出。两者通过category对应。通过一条sql语句实现。如下

with topc AS
(
 SELECT * from(
 select top 4  ROW_NUMBER() over (order by Orders desc) as rownum,ID from Category_30
 ) t1
)
select t.Class_Name,t.CreateTime,b.CategoryName from (
select top 5 Class_Name,Category,CreateTime from TB_ClassInfo
where  Category in (select id from topc where rownum=1)
union
select top 5  Class_Name,CreateTime from TB_ClassInfo
where  Category in (select id from topc where rownum=2)
union
select top 5 Class_Name,CreateTime from TB_ClassInfo
where  Category in (select id from topc where rownum=3)
union
select top 5 Class_Name,CreateTime from TB_ClassInfo
where  Category in (select id from topc where rownum=4)
) t
inner join Category_30 b
on t.Category=b.ID

简单方式:但是不能保证每一个分类都是取得5条数据。

select top 20 t.Class_Name,b.CategoryName from (
select Class_Name,CreateTime from TB_ClassInfo
where  Category in (SELECT ID from(
 select top 4  ROW_NUMBER() over (order by Orders desc) as rownum,ID from Category_30
 order by Orders desc) t1)
) t
inner join Category_30 b
on t.Category=b.ID

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...