我有一个包含以下字段的表收入
+----+-----------+-------------+---------------+
| id | member_id | amount_paid | datetime_paid |
+----+-----------+-------------+---------------+
我想运行查询以查找前 10 个最大收入天数。实现这一目标的最快方法是什么?该表有很多数据。
问候,
尝试执行它的基本查询:
SELECT DATE(`datetime_paid`) AS `Max Revenue`
FROM `revenue`
ORDER BY `amount_paid` DESC
GROUP BY DATE(`datetime_paid`)
LIMIT 10;
这向您显示了前 10 个最大付费天数。:)
假设您的datetime_paid
列是某种日期或时间类型(请参阅 MySQL 文档),以下应该可以工作。
SELECT SUM( `amount_paid` ) AS `amount`, DATE( `datetime_paid` ) as `date`
FROM yourTable
GROUP BY `date`
ORDER BY `amount` DESC
LIMIT 10
首先,您需要按付款日期对结果进行分组。这可以通过选择DATE(datetime_paid) as payday
,然后按 分组来完成payday
。要获得总数,请选择SUM(amount_paid) as total
。最后,要获得前 10 名,请按total desc
和排序limit 10
。
您的最终查询应如下所示:
SELECT DATE(`datetime_paid`) AS `payday`, SUM(`amount_paid`) AS `total`
FROM `table_name_here`
GROUP BY `payday`
ORDER BY `total` DESC
LIMIT 10
您可能需要将该ORDER BY
行更改为ORDER BY SUM(amount_paid) DESC
,我不记得在排序时是否允许使用字段别名。