MySQL总和和更新

时间:2016-09-09 04:16:47

标签: mysql

早上好

我有一个MySQL表,它看起来像这样。

表:接收

+--------------+-----------+---------+---------+-------+
| DateReceived | ItemCode  | QtyPack | QtyStan | PCS   |
+--------------+-----------+---------+---------+-------+
| 2016-09-09   | DRY000004 | 30.00   | 0.00    | 24.00 |
| 2016-09-09   | DRY000007 | 60.00   | 0.00    | 12.00 |
| 2016-09-09   | DRY000010 | 90.00   | 0.00    | 1.00  |
| 2016-09-09   | DRY000011 | 100.00  | 0.00    | 1.00  |
| 2016-09-09   | DRY000012 | 1.00    | 0.00    | 12.00 |
| 2016-09-09   | DRY000012 | 1.00    | 0.00    | 12.00 |
+--------------+-----------+---------+---------+-------+

和表差异

+-----------+-----------+
| ItemCode  | Receiving |
+-----------+-----------+
| DRY000004 |      NULL |
| DRY000007 |      NULL |
| DRY000010 |      NULL |
| DRY000011 |      NULL |
| DRY000012 |      NULL |
| DRY000013 |      NULL |
| DRY000014 |      NULL |
| DRY000016 |      NULL |
| DRY000017 |      NULL |
| DRY000018 |      NULL |
| DRY000019 |      NULL |
| DRY000020 |      NULL |
| DRY000021 |      NULL |
| EQU000001 |      NULL |
+-----------+-----------+

我的目标是获取QtyPack * PCS + QtyStan的总和,然后将其转移到表格Receiving的列Variance中是我的代码

UPDATE Variance VAR INNER JOIN receiving REv ON VAR.ItemCode = REV.ItemCode 
SET VAR.Receiving = replace(REV.QtyPack, ',', '') * replace(REV.PCS, ',', '') + replace(REV.QtyStan, ',', '')
WHERE VAR.ItemCode = REV.ItemCode and REV.Status = 'Posted' AND rev.DateReceived between '2016-09-09' and 
'2016-09-09';

请忽略where子句中的标准,但如果你想这是Table:Receiving

中我的其他标准

即使代码工作也似乎有问题我收到的数据具有相同的ItemCodeDRY000012 QtyPack 1

要简短地讲述这个问题,这是我的问题

如何在表ItemCode中传输之前对所有Variance求和?例如,在接收转移之前,DRY000012必须变为24。

TYSM未来的帮助

1 个答案:

答案 0 :(得分:0)

UPDATE Variance t1
INNER JOIN
(
    SELECT ItemCode,
           Status,
           DateReceived,
           REPLACE(QtyPack, ',', '') * REPLACE(PCS, ',', '') +
           REPLACE(QtyStan, ',', '') AS amount
    FROM Receiving
) t2
    ON t1.ItemCode = t2.ItemCode
SET t1.Receiving = t2.amount
WHERE t2.Status = 'Posted' AND
      t2.DateReceived BETWEEN '2016-09-09' AND '2016-09-09'

这假设ItemCode仅在Receiving表中出现一次,并且在执行UPDATE之前我们不需要任何类型的聚合。