示例 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
執行結果:
新聞熱點
疑難解答