Fork me on GitHub

【记录】T-SQL 分组排序中取出最新数据

示例 Product 表结构:

示例 Product 表数据:

想要的效果是,以 GroupName 字段分组,取出分组中通过 Sort 降序最新的数据,通过示例数据,可以推算出结果数据的 ID 应该为:7、5、3。

示例 SQL 代码:

select * from Product p where ID=(select top 1 ID from Product where p.GroupName=GroupName order by Sort desc) order by Sort desc

并没有使用 group by 或 distinct,一行代码搞定,但这种方式会造成性能问题。

使用 group by 代码示例:

select p1.* from Product p1 
inner (select MAX(p2.ID) from Product p2 group by p2.GroupName) p3 on p1.ID=p3.ID

执行结果:

posted @ 2014-10-10 18:57  田园里的蟋蟀  阅读(988)  评论(3编辑  收藏  举报