从查询中获取其他列

时间:2013-02-05 08:06:54

标签: sql sql-server-2008-r2

我在下面有一个查询,我在超市数据库上使用SQL Server 2008查看可用于在线销售SAP DB的项目。

SELECT T0.[CodeBars], T0.[ItemName], T3.[Price], T1.[Price], T2.[ItmsGrpNam]
FROM OITM T0 INNER JOIN ITM1 T1 ON T0.ItemCode = T1.ItemCode 
INNER JOIN OITB T2 ON T0.ItmsGrpCod = T2.ItmsGrpCod 
INNER JOIN ITM1 T3 ON T0.ItemCode = T3.ItemCode 
WHERE T0.[U_Online] = 'Y' AND T1.[PriceList] = '3' AND T3.[Pricelist]='1'

查询工作正常,但我想为OnHand项添加另一列。即特定仓库'6'的库存物品,其中所有在线销售商品均来自。超市有8个仓库。 T0.[U_Online] = 'Y'显示在线销售的商品,无论仓库如何。

如何修改下面的查询,以便每返回T0.[CodeBars],我会获得仓库6的Onhand项目的附加列?我有一个额外的表OITW加入。

SELECT T0.[CodeBars], T0.[ItemName], T3.[Price], T1.[Price], T2.[ItmsGrpNam],
T4.OnHand
FROM OITM T0 INNER JOIN ITM1 T1 ON T0.ItemCode = T1.ItemCode 
INNER JOIN OITB T2 ON T0.ItmsGrpCod = T2.ItmsGrpCod 
INNER JOIN ITM1 T3 ON T0.ItemCode = T3.ItemCode 
INNER JOIN OITW T4 ON T0.ItemCode = T4.ItemCode
WHERE T0.[U_Online] = 'Y' AND T1.[PriceList] = '3' AND T3.[Pricelist]='1'
--AND T4.WhsCode = '6'

第一次查询的结果

1 个答案:

答案 0 :(得分:1)

我认为您可能需要LEFT JOIN,如下所示:

SELECT 
  T0.[CodeBars], 
  T0.[ItemName], 
  COALESCE(T3.[Price], T1.[Price]) AS Price, 
  T2.[ItmsGrpNam],
  T4.OnHand
FROM       OITM T0 
LEFT JOIN ITM1 T1 ON T0.ItemCode   = T1.ItemCode   AND T1.[PriceList] = '3'
LEFT JOIN OITB T2 ON T0.ItmsGrpCod = T2.ItmsGrpCod 
LEFT JOIN ITM1 T3 ON T0.ItemCode   = T3.ItemCode   AND T3.[Pricelist] = '1'
LEFT JOIN OITW T4 ON T0.ItemCode   = T4.ItemCode   AND T4.WhsCode = '6'
WHERE T0.[U_Online] = 'Y'