计算 SQL 查询中的值并在同一查询的其他计算中使用这些值

Calculating Values in SQL Query and using those values in other calculations in the same query

我有一个 table 用于存储库存,在显示库存时我想做一些计算,运行 一个子查询,其中 returns 我将在某些情况下使用的值计算。

我的出发点是这样的:

SELECT [lineID]
      ,[SKUNumber]
      ,[ContainerNumber]
      ,[UnitsEaches]
      ,ISNULL((select Sum(QTY) from AllocatedInventory
               Where AllocatedInventory.SKUNumber = Inventory.SKUNumber),0) as 'Allocated'
      ,[Bay]
      ,[Level]
      ,[Position]
      ,[VCP]
      ,[UnitWeight]
      ,[Comments]
      ,[DateReceived]
FROM [dbo].[Inventory]

我要做的第一件事是从UnitsEaches 中减去子查询返回的Allocated amount 来计算AvailableInventory。当我尝试使用 Allocated 添加 SUM 函数时,我收到一条错误消息,提示 Allocated is an invalid column。

排序后,我需要用可用库存除以 VCP 来计算主纸箱。

您不能在定义别名的同一范围内引用别名。在这里,横向连接似乎是最简单的解决方案:

SELECT i.[lineID]
      ,i.[SKUNumber]
      ,[ContainerNumber]
      ,i.[UnitsEaches]
      ,ai.Allocated
      ,i.[UnitsEaches] - ai.Allocated as AvailableInventory
      ,i.[Bay]
      ,i.[Level]
      ,i.[Position]
      ,i.[VCP]
      ,i.[UnitWeight]
      ,i.[Comments]
      ,[DateReceived]
FROM [dbo].[Inventory]
OUTER APPLY (
    SELECT COALESCE(SUM(ai.QTY), 0) allocated
    FROM AllocatedInventory ai
    WHERE ai.SKUNumber = i.SKUNumber
) ai