简体   繁体   English

每天汇总MySQL行

[英]Aggregating MySQL rows by day

I have a MySQL table like this: 我有一个这样的MySQL表:

Payments
+----+---------------------+---------+
| id | date (sorted DESC)  | payment |
+----+---------------------+---------+
|  5 | 2010-03-26 00:00:01 |  100.00 |
|  4 | 2010-03-19 00:00:02 |   55.12 |
|  3 | 2010-03-19 00:00:01 |   20.00 |
|  2 | 2010-03-12 00:00:02 |  320.00 |
|  1 | 2010-03-12 00:00:01 |   64.56 |
+----+---------------------+---------+

How can I aggregate the total payments by day? 如何按天汇总付款总额?

Payments are inserted into the table every week, but they aren't always the exact same time as you can see. 付款每周都会插入表格中,但您所看到的并非总是同一时间。 Can aggregation by day be done natively in MySQL? 每天可以在MySQL中本地完成聚合吗?

The desired result would be: 理想的结果将是:

+------------+----------------+
| date       | total payments |
+------------+----------------+
| 2010-03-26 |         100.00 |
| 2010-03-19 |          75.12 |
| 2010-03-12 |         384.56 |
+------------+----------------+

Thanks in advance. 提前致谢。

You can do 2 things, change the datetype to date, so just storing the date (this might not be possible in your situation). 您可以做两件事,将datetype更改为date,因此只存储日期(在您的情况下可能无法实现)。 Or you can group by reforming the date value so its just the date. 或者,您可以通过重新设置日期值使其仅为日期进行分组。

select date(date), sum(payment)
from payments
group by date(date)
order by date(date) desc
SELECT CONVERT(VARCHAR(10), date , 102) as date,sum(payment ) as total_payment
FROM Payments
GROUP BY  CONVERT(VARCHAR(10), date , 102) 
ORDER BY  CONVERT(VARCHAR(10), date , 102)

should be ok 应该可以

您可以按日期对函数进行分组,因此将完整的datetime转换为仅日期部分,然后按该部分分组,只要该日期在select中,就应该合法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM