mysql - 从 group by 创建的组中选择一个值

标签 mysql sql oracle group-by

我有一个表格如下:

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/

相关文章:

sql - 单个SQL SELECT从一个表行返回多行

sql - ORA-00905 : missing keyword (copied from textbook)

linux - mysqldump 没有转储 MariaDB 5.5 数据库中的表

mysql - 如何在出现特定字符串时删除和更新表字段数据?

mysql - 如何从列日期格式获取特定的日月或年

SQL Server 不带 INTO 插入

sql - Rails 3 在没有模型的情况下执行自定义 SQL 查询

PHP 示例 AJAX 实时搜索

sql - 如何在存储过程中使用插入\删除表?

sql - 分层查询/基于表输入