MYSQL的QTY累积总和

时间:2019-10-08 14:40:12

标签: mysql

此表格数据存在一些问题,我想根据 ItemID 从MySQL中的 firstdate到当前凭证日期,获取数量总数

请帮助...

表格:

VCHID  VCHDATE       ITEMID    QTY
-----------------------------------
A1     2019-01-01    Item A    10
A1     2019-01-01    Item B    10
A1     2019-01-01    Item C     5
B2     2019-01-02    Item A     5
B2     2019-01-02    Item B     5
B2     2019-01-02    Item C     5
C3     2019-01-03    Item A    10
C3     2019-01-03    Item B    10
D4     2019-01-04    Item A     5
D4     2019-01-04    Item C     5
D5     2019-01-04    Item A     5

所需结果:

VCHID  VCHDATE       ITEMID    QTY
-----------------------------------
D4     2019-01-04    Item A    35
D4     2019-01-04    Item C    15

Tyvm。

p.s。

我已经测试过该查询:

SELECT
    t1.VCHID,
    t1.VCHDATE,
    t1.ITEMID,
    s.QTY
FROM 
    testtable t1
JOIN 
    (SELECT DISTINCT
         t.ITEMID,
         SUM(t.QTY) AS QTY
     FROM 
         testtable t
     WHERE 
         t.VCHDATE <= '2019-01-04'
     GROUP BY t.ITEMID) s ON t1.ITEMID = s.ITEMID
WHERE 
    t1.VCHID = 'D4';

但是我不知道子查询如何自动读取voucherdate

(t.VCHDATE <= '2019-04-01')

1 个答案:

答案 0 :(得分:0)

加入查询以获取D4的每个项目的当前凭证日期。

SELECT
  t1.VCHID,
  t1.VCHDATE,
  t1.ITEMID,
  s.QTY
FROM testtable t1
  JOIN (SELECT
      t.ITEMID,
      SUM(t.QTY) AS QTY
    FROM testtable t
    JOIN testtable t2 ON t.ITEMID = t2.ITEMID AND t.VCHDATE <= t2.VCHDATE
    WHERE t2.VCHID = 'D4'
    GROUP BY t.ITEMID) s
    ON t1.ITEMID = s.ITEMID
WHERE t1.VCHID = 'D4';

DEMO