【问题标题】:Calculating Values in SQL Query and using those values in other calculations in the same query在 SQL 查询中计算值并在同一查询中的其他计算中使用这些值
【发布时间】:2020-09-21 19:27:28
【问题描述】:

我有一个用于存储库存的表,在显示库存时我想做一些计算,并运行一个返回值的子查询,我将在一些计算中使用。

我的出发点是这样的:

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 添加 SUM 函数时,我收到一条错误消息,提示 Allocated 列无效。

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

【问题讨论】:

  • 样本数据和期望的结果会有很大帮助。

标签: sql sql-server sum subquery


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多