SQL分组排序 -转载
2012-07-09 09:15 沐海 阅读(522) 评论(0) 编辑 收藏 举报不得不承认,我脑子梗塞的很严重。。。
表[gcc_blogInfo]
blogid uid blogtitle createtime issketch checkright
1 1 "hello" 2010-04-01 2 1
2 1 "hello2" 2010-04-02 2 1
3 1 "hello3" 2010-04-03 2 2
4 2 "hello4" 2010-04-01 2 1
5 2 "hello5" 2010-04-05 2 1
6 3 "hello6" 2010-04-01 1 1
7 3 "hello7" 2010-04-02 2 1
最后查询结果为:
blogid uid blogtitle createtime issketch checkright
2 1 "hello2" 2010-04-02 2 1
5 2 "hello5" 2010-04-05 2 1
7 3 "hello7" 2010-04-02 2 1
[c-sharp] view plaincopyprint?
- /*比较好理解哈:就是通过嵌套查询以uid为分组依据,结合最大聚集函数max(...)的使用先得到满足条件的uid,createtime数据集合再以此为依据查询满足条件的值^-^*/select a.blogid,a.uid,a.blogtitle,a.createtime from[gcc_blogInfo] a,(select uid,max(createtime) createtime from [gcc_blogInfo] where issketch=2 and checkright=1 group by uid) b wherea.uid = b.uid and a.createtime = b.createtime/*e-e同事写的可牛啦,我至今未看懂语句短,功效好*/select * from gcc_blogInfo ta where createTime in (select max(createTime) from gcc_blogInfo tb where tb.uid=ta.uid and issketch=2 and checkright=1 )
分组:
[A]表 [B]表
要求输出每个学科前2名学生信息,分数
[sql] view plaincopyprint?
- select b1.subject, b1.score, a.* from b b1 left join a on a.id = b1.id
- where b1.id in(
- select id from b where score in
- (select distinct top 2 score from b where subject=b1.subject order by score desc))
- order by b1.subject,b1.score desc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库