mysql查询组按天计算在时间戳上

时间:2018-01-20 11:37:37

标签: mysql

我有下表:

id   income created_at
-----------------------
966  300    1516182896
965  -1050  1516188513
964  2000   1516444061
963  600    1513267843

我正在运行以下查询以获取每日收入总和(过去10天):

SELECT sum(income) AS income, `created_at`
FROM `incomes`
WHERE `created_at` BETWEEN (UNIX_TIMESTAMP(NOW() - INTERVAL 10 DAY))
  AND UNIX_TIMESTAMP(NOW())
GROUP BY DATE(FROM_UNIXTIME("created_at"))

我得到:

income  created_at
-------------------
1850    1516182896

它给出了总和,无论日期与最后一个created_at有关。

我在那里错过了什么?

3 个答案:

答案 0 :(得分:2)

您正在转换字符串created_at - 删除引号或使用mysql转义字符(反引号)。注意创建时仍然是不确定的你可能应该选择DATE(FROM_UNIXTIME(created_at))

答案 1 :(得分:2)

SELECT sum(income) AS income, DAYOFYEAR(FROM_UNIXTIME(created_at)) as doy
FROM `incomes`
WHERE `created_at` BETWEEN (UNIX_TIMESTAMP(NOW() - INTERVAL 10 DAY))
  AND UNIX_TIMESTAMP(NOW())
GROUP BY doy;

您通过varchar "created_at"而非列created_at进行分组,从而产生了错误。

答案 2 :(得分:0)

你应该添加日期来选择:

SELECT sum(income) AS income, `created_at`, DATE(FROM_UNIXTIME(`created_at`)) as dd
FROM `incomes`
WHERE `created_at` BETWEEN (UNIX_TIMESTAMP(NOW() - INTERVAL 10 DAY))
  AND UNIX_TIMESTAMP(NOW())
GROUP BY dd