我有2个具有相同字段但数据不准确的表。我发现了价格上的差异,但我如何总结这个领域"差异"作为一个不同的领域,我可以报告方差的总和。
SELECT
a.barcode AS BarcodeSUS,
a.sell AS PriceSUS,
b.price AS PricePOS,
a.sell-b.price AS difference
FROM SUS AS a LEFT JOIN POS AS b ON a.barcode = b.barcode
ORDER BY b.price;
答案 0 :(得分:0)
如果你想要每行的累计值,这应该可以解决问题:
SELECT
a.barcode AS BarcodeSUS
, a.sell AS PriceSUS
, b.price AS PricePOS
, a.sell-b.price AS difference
, (SELECT
SUM(SUS.sell-POS.price)
FROM SUS
LEFT JOIN POS ON SUS.barcode = POS.barcode
WHERE SUS.barcode <= a.barcode
) AS [accumulated difference]
FROM SUS AS a
LEFT JOIN POS AS b ON a.barcode = b.barcode
ORDER BY a.barcode;
如果您只想要总差额:
SELECT
a.barcode AS BarcodeSUS
, a.sell AS PriceSUS
, b.price AS PricePOS
, a.sell-b.price AS difference
, (SELECT
SUM(SUS.sell-POS.price)
FROM SUS
LEFT JOIN POS ON SUS.barcode = POS.barcode
) AS [total difference]
FROM SUS AS a
LEFT JOIN POS AS b ON a.barcode = b.barcode
ORDER BY a.barcode;