MySQL Group By Day by Day

时间:2012-01-09 20:25:48

标签: mysql sql

我有一张表

id int pk auto_inc | created int(11) | amount int | user_id int

我想创建一个按天分组的行列表,总计金额字段。

我试过这个:

SELECT created, sum(amount) as amount, id FROM total_log WHERE user_id = $this->user_id GROUP BY DAY(created)

这不会给出正确的结果。它们被分成一行。

日期从dd / mm / yyyy格式保存到unix时间戳,如1349046000

3 个答案:

答案 0 :(得分:4)

SELECT 
    DATE(FROM_UNIXTIME(created)) as d, 
    sum(amount) as amount
FROM total_log 
WHERE user_id = $this->user_id 
GROUP BY d

答案 1 :(得分:1)

MySQL不喜欢混合dayint列:

mysql> select day(1349046000);
+-----------------+
| day(1349046000) |
+-----------------+
|            NULL |
+-----------------+
1 row in set, 1 warning (0.00 sec)

mysql> show warnings;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1292 | Incorrect datetime value: '1349046000' |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)

因此,NULL的所有行都会day(some_int_value),并且它们都会在同一组中。

我建议改为使用该列的datedatetime类型。

此外,不应在group by语句中引用不在select子句中的列,除非在它们上使用聚合函数。

答案 2 :(得分:1)

SELECT 
DAY(DATE(FROM_UNIXTIME(created))), 
sum(amount) as amount 
FROM total_log 
WHERE user_id = $this->user_id 
GROUP BY DAY(DATE(FROM_UNIXTIME(created)))