我有一个表格如下:
bill_id | date | bill_amount
1234 | 20-06-2013 | 800
1200 | 18-06-2013 | 1500
1000 | 15-05-2013 | 2000
950 | 10-05-2013 | 2500
900 | 20-04-2013 | 750
我想显示过去 3 个月的账单。 如果每月有多个账单,我想显示最新的账单(在示例中,6 月的 bill_id 为 1234,5 月的 bill_id 为 1000)。
我可以使用 IN 查询来完成此操作(通过对月份和年份使用 group by 并考虑特定月份年份的最大 bill_id)。但我的问题是,是否可以在单个查询中实现相同的输出?
最佳答案
是的,使用substring_index()
/group_concat()
技巧:
select substring_index(group_concat(bill_id order by date, bill_id desc desc), ',', 1) as bill_id,
max(date) as date,
substring_idnex(group-concat(bill_amount order by date, bill_id desc), ',', 1) as bill_amount
from bills
group by year(date), month(date)
关于mysql - 从 group by 创建的组中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238574/