SQL Server中2个别名的SUM

时间:2018-03-14 02:04:48

标签: sql sum alias sql-server-2016-express

Balance列显示当前现有库存+未结采购数量减去已输入数量。

我在SELECT语句中有ALIASes的现有查询:

SELECT dbo.Items.ItemNo, 
       dbo.Items.Name, 
       dbo.Vendors.Name AS VendorName, 
       ISNULL(ItemsStock.StockOnHand, 0) AS [Stock on Hand], 
       ISNULL(PO.[Open PO's'], 0) AS [Open PO], 
       ISNULL(WO.OpenWOQTY, 0) AS [QTY Entered].

如何添加一个名为Balance的额外列来累计库存和打开采购订单,然后扣除已输入的数量?

2 个答案:

答案 0 :(得分:0)

SELECT dbo.Items.ItemNo, 
       dbo.Items.Name, 
       dbo.Vendors.Name AS VendorName, 
       ISNULL(ItemsStock.StockOnHand, 0) AS [Stock on Hand], 
       ISNULL(PO.[Open PO's'], 0) AS [Open PO], 
       ISNULL(WO.OpenWOQTY, 0) AS [QTY Entered],
       ISNULL(ItemsStock.StockOnHand, 0) + ISNULL(PO.[Open PO's'], 0) - ISNULL(WO.OpenWOQTY, 0) AS [Balance]
FROM table

答案 1 :(得分:0)

三点建议:

  1. 使用表别名。
  2. 使用coalesce()代替isnull()coalesce()是ANSI标准。
  3. 使用不需要转义的列名称。
  4. 这看起来像:

    SELECT i.ItemNo, i.Name, v.Name AS VendorName, 
           COALESCE(is.StockOnHand, 0) AS Stock_on_Hand, 
           COALESCE(PO.[Open PO's'], 0) AS Open_PO, 
           COALESCE(WO.OpenWOQTY, 0) AS QTY_Entered,
           (COALESCE(is.StockOnHand, 0) + COALESCE(PO.[Open PO's'], 0) - COALESCE(WO.OpenWOQTY, 0) as Balance
    FROM dbo.Items i JOIN
         dbo.Vendors v
         . . .
    

    如果您不想重复别名,传统方法是使用CTE或子查询。 SQL Server还提供了横向连接,引入了apply关键字:

    SELECT i.ItemNo, i.Name, v.Name AS VendorName, 
           vals.Stock_on_Hand, vals.Open_PO, vals.QTY_Entered,
           (vals.Stock_on_Hand + vals.Open_PO - vals.QTY_Entered) as Balance
    FROM dbo.Items i JOIN
         dbo.Vendors v
         . . . CROSS APPLY
         (VALUES ( COALESCE(is.StockOnHand, 0), COALESCE(PO.[Open PO's'], COALESCE(WO.OpenWOQTY, 0))
         ) vals(Stock_on_Hand, Open_PO, QTY_Entered);