如何使用SQL从2个字段的总和中获取总计?

时间:2019-05-21 10:48:16

标签: sql sql-server

这是我创建的sql

SELECT SUM(SupplierItems.SupplierItemCost +
           SupplierItems.SupplierItemInventory
          ) AS TotalCost
FROM SupplierItems 
GROUP BY SupplierItems.ID

上面的sql获取两个字段的总和,即itemcost和iteminventory,这就是结果

TotalCost
1000
2000
3000

我需要从TotalCost获取所有的总和。

谢谢

3 个答案:

答案 0 :(得分:2)

如果要在表中显示总计,请删除GROUP BY

SELECT SUM(si.SupplierItemCost +
           si.SupplierItemInventory
          ) AS TotalCost
FROM SupplierItems si;

但是要小心。如果任何基础值是NULL,则可能无法获得正确的结果。这样做更安全:

SELECT (COALESCE(SUM(si.SupplierItemCost), 0) +
        COALESCE(SUM(si.SupplierItemInventory, 0)
       ) AS TotalCost
FROM SupplierItems si;

答案 1 :(得分:1)

如果要总计,则可以不使用 GROUP BY

SELECT SUM(SupplierItems.SupplierItemCost +
           SupplierItems.SupplierItemInventory
          ) AS TotalCost
FROM SupplierItems

如果要基于 SupplierItems.ID 进行部分总计,则可以使用 GROUP BY

SELECT SupplierItems.ID,SUM(SupplierItems.SupplierItemCost +
           SupplierItems.SupplierItemInventory
          ) AS TotalCost
FROM SupplierItems 
GROUP BY SupplierItems.ID

答案 2 :(得分:1)

如果要在其他行中查看所有TotalCost的总和,则可以使用ROLLUP

SELECT SupplierItems.ID, SUM(SupplierItems.SupplierItemCost +
           SupplierItems.SupplierItemInventory
          ) AS TotalCost
FROM SupplierItems 
GROUP BY ROLLUP(SupplierItems.ID)