我正在尝试创建累积列但无法创建它,请查看我尝试计算的内容。
mytable
SELECT TotalQuantity AS DistinctTotalQuantity,
COUNT(TotalQuantity) AS COUNTVALUE,
@running_total := @running_total + COUNT(TotalQuantity) AS cumulative_sum
FROM mytable
JOIN (SELECT @running_total := 0) r
GROUP BY TotalQuantity
根据以上数据集,我想计算明显的计数和累计和
join()
答案 0 :(得分:2)
执行累积和的规范ANSI标准方法是通过相关子查询。我在这里使用了一个包含基本查询的视图:
CREATE VIEW test AS
SELECT
TotalQuantity AS DistinctTotalQuantity,
COUNT(TotalQuantity) AS COUNTVALUE,
FROM mytable
WHERE StoreId = 210 AND ProdName = 'Tusq'
GROUP BY TotalQuantity
然后通过以下方式计算运行总计:
SELECT
t1.DistinctTotalQuantity,
t1.COUNTVALUE,
(SELECT SUM(t2.COUNTVALUE) FROM test t2
WHERE t2.DistinctTotalQuantity <= t1.DistinctTotalQuantity) AS cumulative_sum
FROM test t1;
使用会话变量我们可以尝试:
SET @total = 0;
SELECT
DistinctTotalQuantity,
COUNTVALUE,
(@total := @total + COUNTVALUE) AS cumulative_sum
FROM test;
答案 1 :(得分:1)
以下查询将完美运行,并且您的查询/方法不需要进行太多更改。虽然,我对表现不太确定:
SELECT TotalQuantity AS DistinctTotalQuantity,
COUNT(TotalQuantity) AS COUNTVALUE,
(select @running_total := @running_total + count(TotalQuantity) from mytable m
where m.TotalQuantity = m1.TotalQuantity) cumulative_sum
FROM (select *from mytable order by TotalQuantity) m1
JOIN (SELECT @running_total := 0) r
GROUP BY m1.TotalQuantity;
如果要使用浮动值,请按如下方式声明列:
create table `mytable` (
`TotalQuantity` Decimal (7,1) //Here 1 is scale. It means 1 digit is allowed after decimal point.
)
这是我更新的Sqlfiddle
希望它有所帮助!
答案 2 :(得分:0)
set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;
set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from mytable
order by id;