如何根据月份分组MySql行?

时间:2010-04-05 19:17:31

标签: php mysql group-by

我有一个表格,其中包含日期时间(格式:'Y-m-d H:i:s')'已创建'字段和每行中的'金额'(整数)字段。现在我想找出去年的月份总金额。我怎么能这样做?

修改

我做了一个编辑来澄清实际问题。所以基本上我想知道每个月的总金额,但仅限于去年。

EDIT2

去年意味着过去365天。那么在某个地方我要考虑“当天”?

EDIT3

我的不好,实际上去年是过去12个月。所以天数将在336到365之间。

3 个答案:

答案 0 :(得分:8)

试试这个(更新以回答“edit3”):

SELECT
    YEAR(created) as year,
    MONTH(created) AS month,
    SUM(amount) AS total_amount
FROM table1
WHERE created
    BETWEEN DATE(NOW()) - INTERVAL (DAY(NOW()) - 1) DAY - INTERVAL 11 MONTH
    AND NOW()
GROUP BY YEAR(created), MONTH(created)
ORDER BY YEAR(created), MONTH(created);

示例结果(2010年4月运行时):

year  month  total_amount
2009  5      26
2010  1      20

另请注意,根本不会返回没有条目的月份(而不是以total_amount = 0返回)。

测试数据:

CREATE TABLE table1 (created datetime NOT NULL, amount INT NOT NULL);
INSERT INTO table1 (created, amount) VALUES
('2010-01-01 13:56:23', 5),
('2010-01-04 13:56:23', 15),
('2009-05-04 13:56:23', 26);

答案 1 :(得分:2)

这将返回去年的计数和总金额:

SELECT MONTH(created) as month_updated,
  COUNT(created) as month_updates, SUM(amount) as month_total FROM table
WHERE created BETWEEN DATE_ADD(NOW(), INTERVAL -1 YEAR) AND NOW()
GROUP BY MONTH(created)

或者,如果你特意指的是2009年:

SELECT MONTH(created) as month_updated,
  COUNT(created) as month_updates, SUM(amount) as month_total FROM table
WHERE created BETWEEN '2009-01-01 00:00:00' AND '2009-12-31 23:59:59'
GROUP BY MONTH(created)

答案 2 :(得分:0)

SELECT count(some_row) AS or_whatever FROM your_table GROUP BY MONTH(update);

更具体(使用您的更新):

SELECT SUM(amount) FROM table_name GROUP BY MONTH(created);