我有一张表
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
答案 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不喜欢混合day
和int
列:
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)
,并且它们都会在同一组中。
我建议改为使用该列的date
或datetime
类型。
此外,不应在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)))