sql查询groupby分组后获得每组中时间最⼤记录直接上最终sql
id为数据唯⼀键,storage_time为时间戳,application_matters为分组依据groupby分组
SELECT
*
FROM
csrc_approved_products_weekly
WHERE
id IN (
SELECT SUBSTRING_INDEX(group_concat( id ORDER BY `storage_time` DESC ), ',', 1 )
FROM csrc_approved_products_weekly
GROUP BY application_matters
)
解析
1.按时间从⼤到⼩顺序取出唯⼀键id列表
SELECT
group_concat( id ORDER BY `storage_time` DESC )
FROM
csrc_approved_products_weekly
GROUP BY
application_matters
2.再⽤SUBSTRING_INDEX函数取出第⼀个(也就是时间最⼤的数据id)
SELECT
SUBSTRING_INDEX( group_concat( id ORDER BY `storage_time` DESC ), ',', 1 )
FROM
csrc_approved_products_weekly
GROUP BY
application_matters
3.再根据 id查询数据
SELECT
*
FROM
csrc_approved_products_weekly
WHERE
id IN (
SELECT SUBSTRING_INDEX( group_concat( id ORDER BY `storage_time` DESC ), ',', 1 )
FROM csrc_approved_products_weekly
GROUP BY application_matters
)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论