仅一年的数据

时间:2014-10-14 06:27:25

标签: mysql sql

这是我捐赠的表格。

SELECT nid, SUM(amount) as sum, month 
FROM `donate` 
where nid = 1221 
  and payment_status = 'completed'
  and date >= 1388534400
group by month

+----------------------------------------------------+
| nid  | amount| date       | month | payment_status |
| 1221 |  80   | 1388534400 | jan-14 | completed     |
| 1221 |  60   | 1388534400 | jan-14 | completed     |
| 1221 |  90   | 1388534400 | apr-14 | completed     |
| 1221 |  80   | 1388534400 | aug-14 | completed     |
| 1221 |  90   | 1388534400 | dec-14 | completed     |
| 1221 |  100  | 1388534400 | dec-13 | completed     |
+----------------------------------------------------+

1388534400是Wed,01 Jan 2014 00:00:00 GMT的日期戳

我想在一年内填充数据,现在如果我在查询之上运行,那么我将得到dec-13的数据,这是我不想要的。

+--------+-------+------+---------+----+---------+
| 1221|  100  |dec-13 |completed      |
+--------+-------+------+---------+----+---------+

我希望数据只能来一年。不止于此。

4 个答案:

答案 0 :(得分:0)

SELECT nid, SUM(amount) as sum, month 
FROM votesane_donate 
WHERE nid = 1221 AND payment_status = 'completed' AND Year(date) = Year(NOW()) 
GROUP BY month

这将选择今年的记录。

使用Wojciech的答案选择去年(过去12个月)的记录。

答案 1 :(得分:0)

尝试使用DATE_SUB

SELECT nid, SUM(amount) as sum, month  FROM `votesane_donate` 
WHERE nid = 1221 
AND payment_status = 'completed'
AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR)
GROUP BY month

假设date字段属于TIMESTAMP类型,而不是INTEGER

答案 2 :(得分:0)

尝试使用 TIMESTAMPDIFF()

SELECT nid, SUM(amount) as sum, month 

FROM `votesane_donate` 

WHERE nid = 1221 AND payment_status = 'completed'

AND (TIMESTAMPDIFF(YEAR, DATE_FORMAT(FROM_UNIXTIME(date),'%Y-%m-%d %H:%i:%s'), NOW()))) = 1

GROUP BY month

答案 3 :(得分:0)

以下查询将返回您需要的内容。 如果您需要删除“nid = 1221”条件,此查询还会确保使用“日期”列中的索引,从而加快查询速度:

SELECT nid, SUM(amount), month
FROM votesane_donate
WHERE
    nid = 1221
    AND payment_status = 'completed'
    AND date > UNIX_TIMESTAMP(CONCAT(YEAR(CURRENT_DATE) - 1, '-12-31 23:59:59'))
    AND date < UNIX_TIMESTAMP(CONCAT(YEAR(CURRENT_DATE) + 1, '-01-01 00:00:00'))
GROUP BY nid, month