如何根据月份对MySql行进行分组? [英] how to group MySql rows based on month?

查看:182
本文介绍了如何根据月份对MySql行进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在每一行中都有一个带有日期时间(格式:'Y-m-d H:i:s')'创建'字段和'数量'(整数)字段的表。现在我想在去年找出明智的总金额。我怎样才能做到这一点?

编辑



实际的问题。所以基本上我想知道每个月的总金额,但仅限于过去一年。



EDIT2



去年意味着最后365天。那么我需要考虑的一个地方是当日?
$ b $ p EDIT3



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

解决方案

试试这个(更新回答你的edit3):

 选择
YEAR(创建)为年,
MONTH(创建)AS月,
SUM (金额)AS total_amount
FROM table1
WHERE创建
间隔(现在()) - 间隔(天(现在()) - 1)日 - 区间11个月
和NOW()
GROUP BY YEAR(创建),MONTH(创建)
ORDER BY YEAR(创建),MONTH(创建);

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

  year month total_amount 
2009 5 26
2010 1 20

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

测试数据:

  CREATE TABLE table1(创建日期时间NOT NULL,金额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);


I've a table with a datetime (format: 'Y-m-d H:i:s') 'created' field and 'amount' (integer) field in each row. Now I want to find out month wise total 'amount' in last year. How can I do this?

EDIT

I made an edit to clarify the actual problem. so basically I want to know total 'amount' in each month, but only for the last year.

EDIT2

Last year means last 365 days. So somewhere I've to consider 'current day'?

EDIT3

My bad, actually last year is last 12 months. So number of days would be between 336 and 365.

解决方案

Try this (updated to answer your "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);

Example result (when run in April 2010):

year  month  total_amount
2009  5      26
2010  1      20

Note also that months with no entries will not be returned at all (rather than being returned with total_amount = 0).

Test data:

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);

这篇关于如何根据月份对MySql行进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆