每行的行日期之前的句点的Mysql总和

时间:2013-06-04 13:27:01

标签: mysql

我在mysql中有一个表格,其中列有日期,收入,以及当月每天产生的收入 我需要把它变成格式 日期,“此日期之前的收入总和”

我可以用

来做
select max(date) as date, sum(revenue) as total_revenue_to_date from table where dayofmonth(date)<=1
union
select max(date) as date, sum(revenue) as total_revenue_to_date from table where dayofmonth(date)<=2
.......

等,但想以更好的格式编写。

有人有什么想法吗?

asnwered: 最短,最容易遵循:

SELECT fulldate, 
(SELECT SUM(margin) FROM fact_agg_margin_live_daily d2 WHERE d1.fulldate>=d2.fulldate) AS margin 
FROM fact_agg_margin_live_daily d1

2 个答案:

答案 0 :(得分:2)

我做了一些测试,所以这是我的例子:

表名= materiales 字段名称= id_material

行:1,2,3,4,6,7,9(列id_material)

使用的查询:

SELECT id_material, (SELECT SUM(id_material)FROM materiales M2 WHERE M1.id_material&gt; = M2.id_material)AS suma 从materiales M1

预期结果:column1具有当前id,column2具有当前id的结果加上前一个的结果,是的,它可以工作。

您可以将其更改为当前场景,如下所示:

选择日期, (SELECT SUM(收入)FROM表T2 WHERE T1.date&gt; = T2.date)AS revenue_until_current_date 从表T1

这将返回每个日期的收入,直到该日期为止。如果每天存储行,它将每天返回当天的收入加上前一天的收入。

答案 1 :(得分:1)

group by用于查询会更加简单:

select max(date) as date, sum(revenue) as total_revenue_to_date
from table
group by dayofmonth(date)

您想要累积总和(您的查询不会这样做)。这是一种方法(用30天的月份说明):

select max(date) as date, sum(revenue) as total_revenue_to_date
from t join
     (select 0 as n union all select 1 union all select 2 union all select 3 union all select 4 union all
      select 5 as n union all select 6 union all select 7 union all select 8 union all select 9 union all
      select 10 as n union all select 11 union all select 12 union all select 13 union all select 14 union all
      select 15 as n union all select 16 union all select 17 union all select 18 union all select 19 union all
      select 20 as n union all select 21 union all select 22 union all select 23 union all select 24 union all
      select 25 as n union all select 26 union all select 27 union all select 28 union all select 29 union all
      select 30
     ) n
     on day(date) + n <= 30
group by day(date) + n;

您也可以使用变量执行此操作:

  select max(date) as date, sum(revenue) as total_revenue_to_date,
         @sum := @sum + SUM(revenue) as cumsum
  from table cross join
       (select @sum := 0) const
  group by dayofmonth(date)