2017-10-14 97 views
2

我正在尝试创建累积式列但无法创建它,请看看我试图计算它。在mysql中计算累积式公式

MYTABLE

create table mytable (
    TotalQuantity Decimal(7) 
); 
insert into mytable (TotalQuantity) values 
(0.0), 
(0.0), 
(1.0), 
(0.0), 
(2.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(0.0), 
(1.0), 
(1.0), 
(0.0), 
(1.0); 

enter image description here

基于上述数据集我想计算不同明智计数和累加和

enter image description here

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 
+0

尝试https://stackoverflow.com/questions/12668785/cumulating-value-of-current-row-sum-of-previous-rows – davidchoo12

+0

您正在合并两种方法。既可以在子查询中进行分组,也可以在外部查询中进行变量添加,或切换到仅使用其中一种或其他方法。 – Strawberry

+0

@ davidchoo12我怀疑OP的mysql版本是最新版本 – Strawberry

回答

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

希望它可以帮助!

+0

嘿Harshil,如果价值改变就会出错。 http://sqlfiddle.com/#!9/95166f/1 –

+0

好的。让我检查一下。 –

+0

问题解决了:http://sqlfiddle.com/#!9/95166f/6/0 –

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; 
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; 
+0

查询看起来太贵,我们不能用变量做同样的事吗? –

+0

@JunedAnsari如果需要,您可以使用会话变量来计算滚动总和。但是这里性能问题的一部分是你需要在一个查询中进行聚合,然后进行滚动求和。这不是最高性能的情况。 –