mysql中更复杂的累积和列

时间:2011-04-19 03:12:42

标签: mysql select

我读了Create a Cumulative Sum Column in MySQL,并试图让它适应我正在做的事情,但我似乎无法做到正确。

表格:

Id (primary key)
AcctId
CommodId
Date
PnL

有一个唯一的索引包含AcctId,CommodId,Date。我想获得按日期分组的累计总数。

此查询

select c.date
   , c.pnl
   ,(@cum := @cum + c.pnl) as "cum_pnl"
   from commoddata c join (select @cum := 0) r
   where
   c.acctid = 2
   and
   c.date >= "2011-01-01"
   and
   c.date <= "2011-01-31"
   order by c.date

将正确计算所有记录的运行总计,以

格式显示数据
date        pnl       cum_pnl
========    ======    =======
2011-01-01       1          1
2011-01-01       1          2
2011-01-01       1          3
2011-01-01       1          4
2011-01-02       1          5
2011-01-02       1          6
...

(每个日期可以有很多记录)。我想要的是

date        cum_pnl
========    =======
2011-01-01       4
2011-01-02       6
...

但我没有尝试过的任何作品。 TIA。

2 个答案:

答案 0 :(得分:2)

或者我认为您可以将所有pnl替换为sum(pnl),并让@cum跨越这些。我认为它看起来像这样:

select c.date
   ,SUM(c.pnl)
   ,(@cum := @cum + SUM(c.pnl)) as "cum_pnl"
   from commoddata c join (select @cum := 0) r
   where
   c.acctid = 2 and c.date >= "2011-01-01" and c.date <= "2011-01-31"
   order by c.date
   GROUP BY c.date

我只是想弄清楚当SQL不是按表达式分组时,SQL是否会让你对选择cum_pnl感到悲伤...也许你可以尝试按它分组?

编辑新主意,如果您真的不反对嵌套查询,请使用求和的分组查询替换commoddata

select c.date
   ,c.pnl
   ,(@cum := @cum + c.pnl) as "cum_pnl"
   from 
       (SELECT date, sum(pnl) as pnl FROM commoddata WHERE [conditions] GROUP BY date) c 
       join (select @cum := 0) r
   order by c.date

答案 1 :(得分:0)

可能不是最好的方法,但你可以SELECT Date, MAX(Cum_PnL) FROM (existing_query_here) GROUP BY Date