简体   繁体   中英

Aggregating MySQL rows by day

I have a MySQL table like this:

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?

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). 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中,就应该合法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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