xishuai

示例 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

执行结果:

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-10-19
  • 2021-08-15
  • 2022-12-23
  • 2021-07-02
  • 2021-11-28
  • 2021-06-14
  • 2022-01-01
猜你喜欢
  • 2021-10-07
  • 2021-10-17
  • 2021-08-15
  • 2022-12-23
  • 2021-08-15
相关资源
相似解决方案