当前位置:   article > 正文

Mysql分组查询每组最新的一条数据_mysql分组取出每组最新一条数据

mysql分组取出每组最新一条数据

在工作中遇到一个问题,需要查出每个公司最新的那条数据。

所以需根据公司进行分组: 

未进行分组时:

  1. select a.id, b.name companyName, result_asset ,result_liability ,result_net_asset, a.create_time ,a.is_deleted
  2. from bus_property_appraisal_approve a
  3. join bas_company b on a.company_id = b.id
  4. where a.is_deleted = 0 and b.is_deleted = 0 and a.status > 0

分组查询后:  

  1. select a.id, b.name companyName, result_asset ,result_liability ,result_net_asset
  2. from bus_property_appraisal_approve a
  3. join bas_company b on a.company_id = b.id
  4. join (select MAX(id) as id from bus_property_appraisal_approve where is_deleted = 0 and status > 0 group by company_id) c on a.id = c.id
  5. where a.is_deleted = 0 and b.is_deleted = 0 and a.status > 0
  6. order by result_asset

简化一下sql语句:

  1. SELECT
  2. t1.*
  3. FROM
  4. customer_wallet_detail t1
  5. INNER JOIN ( SELECT MAX( id ) AS id FROM customer_wallet_detail GROUP BY customer_id ) t2
  6. ON t1.id = t2.id

 

参考文章:

Mysql分组查询每组最新的一条数据(五种实现方法)_mysql group by 取最新的一条_kerwin_code的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/952691
推荐阅读
相关标签
  

闽ICP备14008679号