0

我在 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
4

2 回答 2

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>=M2.id_material) AS suma FROM materiales M1

预期结果:column1 具有当前 id,column2 具有当前 id 加上前一个结果的总和,是的,它有效。

您可以以某种方式将其更改为您当前的情况,如下所示:

SELECT date, (SELECT SUM(revenue) FROM table T2 WHERE T1.date >= T2.date) ASincome_until_current_date FROM table T1

这将返回每个日期以及该日期之前的收入。如果每天都存储这些行,它将每天返回当天的收入加上前一天的收入。

于 2013-06-04T14:09:21.063 回答
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)
于 2013-06-04T13:28:49.220 回答