我想知道最好的方法是累计到目前为止一年中每个月的一些数字,然后打印信息。
我的桌子目前看起来像这样 表格名称:支出
列是日期|付费
然后我希望它把每个月的“付费”列中的所有数字加起来,并像这样打印
January : 100,000
February : 2,300
e.t.c
这可能吗?
答案 0 :(得分:0)
您可以对月份进行汇总和分组。
select month, sum(amount) from `data_values` group by month
查看实际情况http://sqlfiddle.com/#!9/0bd27/2
create table `data_values` (month varchar(50), amount decimal(18,2));
insert into `data_values` (month, amount) values ('January', 100),
('January', 50),
('Februari', 100),
('March', 100),
('April', 100),
('May', 100),
('May', 50),
('May', 25);
select month, sum(amount) from `data_values` group by month
month sum(amount)
April 100
Februari 100
January 150
March 100
May 175
现在,如果表中有实际日期字段,则可以使用monthname()
来获取所需的分组
查看实际情况http://sqlfiddle.com/#!9/09a1d6/1
create table `data_values` (buy_date date, amount decimal(18,2));
insert into `data_values` (buy_date, amount) values ('2008-01-01', 100),
('2008-01-14', 50),
('2008-02-15', 100),
('2008-03-01', 100),
('2008-04-01', 100),
('2008-05-02', 100),
('2008-05-10', 50),
('2008-05-22', 25);
select monthname(buy_date), sum(amount) from `data_values` group by monthname(buy_date)
monthname(buy_date) sum(amount)
April 100
February 100
January 150
March 100
May 175
您可能想添加一个附加的year(pay_date)
子句,以免将年份混在一起。除非那是您想要的。参见http://sqlfiddle.com/#!9/9acc82/2 select year(buy_date), monthname(buy_date), sum(amount) from data_values group by year(buy_date), monthname(buy_date)