上一年的SQL运行总数

时间:2018-08-13 06:45:55

标签: mysql sql

如何从此查询中运行总计或累计金额?是否可以通过相关子查询运行?累计总和结果将显示为“新值”。

SELECT
  sum(data2.quantity/1000) AS UnitMT
FROM
  data2
INNER JOIN itmnocate ON data2.item = itmnocate.ItemNumber
                    and Source in ('imported','local','by product')
WHERE date1 >= DATE_FORMAT('2018-04-12', '%Y-01-01')- INTERVAL 1 YEAR 
 AND date1 <= DATE_FORMAT('2018-04-12', '%Y-12-31') - INTERVAL 1 YEAR
 AND data2.unit = 'KG'
 and data2.customeracc not in (select Customeraccount from custlist WHERE Custcat = 'bcsb')
GROUP BY month(date1)

Expected Result

3 个答案:

答案 0 :(得分:0)

这是一个累积性问题,如果您的mysql版本支持window function,则可以将SUM与窗口功能一起使用来累积。

DATE1列可用作order by进行累加的基础。

SELECT *,
       sum(UnitMT) over (order by month(date1)) 'New value'
FROM T t1 

sqlfiddle


如果您的mysql版本不支持窗口功能,则可以尝试在select中使用子查询来进行累积。

CREATE TABLE T( date1 DATE,UnitMT int);

INSERT INTO T VALUES ('2017-01-01',66535);
INSERT INTO T VALUES ('2017-02-01',108337);
INSERT INTO T VALUES ('2017-03-01',132767);
INSERT INTO T VALUES ('2017-04-01',100687);
INSERT INTO T VALUES ('2017-05-01',125151);

查询1

SELECT *,
      (SELECT SUM(UnitMT) FROM T tt WHERE month(tt.date1) <= month(t1.date1)) 'New value'
FROM T t1 

Results

|      date1 | UnitMT | New value |
|------------|--------|-----------|
| 2017-01-01 |  66535 |     66535 |
| 2017-02-01 | 108337 |    174872 |
| 2017-03-01 | 132767 |    307639 |
| 2017-04-01 | 100687 |    408326 |
| 2017-05-01 | 125151 |    533477 |

注意

T代表您当前的结果集数据。

答案 1 :(得分:0)

您可以尝试以下查询,它效率高且可以使用所有MySQL版本:

select @cumSum := 0;

select UnitMT, @cumSum := @cumSum + UnitMT
from tbl
order by date1;

Demo

答案 2 :(得分:0)

对于您的特定问题,可以使用变量和子查询:

SELECT mon, UnitMT,
       (@sum := @sum + UnitMT) as running_sum
FROM (SELECT month(date1) as mon, sum(data2.quantity/1000) AS UnitMT
      FROM data2 INNER JOIN
           itmnocate
           ON data2.item = itmnocate.ItemNumber AND
              Source IN ('imported', 'local', 'by product')
      WHERE date1 >= DATE_FORMAT('2018-04-12', '%Y-01-01') - INTERVAL 1 YEAR AND
            date1 <= DATE_FORMAT('2018-04-12', '%Y-12-31') - INTERVAL 1 YEAR AND
           data2.unit = 'KG' AND
           data2.customeracc not in (select Customeraccount from custlist WHERE Custcat = 'bcsb')
      GROUP BY month(date1)
      ORDER BY month(date1)
     ) m CROSS JOIN
     (SELECT @sum := 0) params;