mysql中更复杂的累积和列
我阅读了 在 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。
I read Create a Cumulative Sum Column in MySQL, and tried to adapt it to what I'm doing, but I can't seem to get it right.
The table:
Id (primary key)
AcctId
CommodId
Date
PnL
There is a unique index which contains AcctId, CommodId, Date. I want to get a cumulative total grouped by date.
This query
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
will correctly calculate the running total for all records, showing data in the format
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
...
(there can be many records per date). What I want is
date cum_pnl
======== =======
2011-01-01 4
2011-01-02 6
...
But nothing I've tried works. TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
或者,我认为您可以将所有
pnl
替换为sum(pnl)
,并让您的 @cum 运行这些。我认为它看起来像这样:我只是想弄清楚,当 SQL 不是按表达式分组时,SQL 是否会让您因选择 cum_pnl 而感到悲伤...也许您也可以尝试按它分组?
编辑新想法,如果您确实不反对嵌套查询,请将
commoddata
替换为求和分组查询Alternately I think you can replace all your
pnl
withsum(pnl)
, and let your @cum run across those. I think it would look like this:I'm just trying to figure out if SQL will give you grief over selecting cum_pnl when it is not a group by expression... maybe you can try grouping by it as well?
EDIT New Idea, if you're really not averse to nested queries, replace
commoddata
with a summed grouped query可能不是最好的方法,但您可以
SELECT Date, MAX(Cum_PnL) FROM (existing_query_here) GROUP BY Date
Probably not the best way, but you can
SELECT Date, MAX(Cum_PnL) FROM (existing_query_here) GROUP BY Date