微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐