来自不同表的SQL链接值

时间:2018-11-07 11:14:22

标签: sql tsql

所以我有下表

[Items] [I]
[ID] [Date] [Item] [Qty]
1    06/11  Bat    2
2    06/11  Ball   2
3    07/11  Bat    3
4    07/11  Ball   2
5    07/11  Pump   1

[Goods1] [G1]
[ID] [Item] [Date] [Price]
1    Bat    06/11   20.00
2    Bat    07/11   21.00

[Goods2] [G2]
[ID] [Date] [Price]
1    06/11   12.50
2    07/11   12.55

我想加入它们,并从每天中获取价格,但是当我包括[G1]或[G2]表之一的日期时,当我想要空值时,它将被删除。如果我在WHERE函数中都包含了两者,那么我将得到0行。我想要的结果是:

[ID] [Date] [Item] [G1].[Price] [G2].[Price]
3    07/11  Bat    21.00        NULL
4    07/11  Ball   NULL         12.55
5    07/11  Pump   NULL         NULL

我拥有的代码是:

SELECT [I].[ID], [I].[DATE], [I].[ITEM], [BT].[PRICE], [BL].[PRICE] 
FROM [ITEMS] [I]
LEFT JOIN [GOODS1] [G1] ON [I].[ITEM] = [G1].[ITEM]
LEFT JOIN [GOODS2] [G2] ON [I].[ITEM] = [G2].[ITEM]
WHERE [I].[DATE] = '2018-11-07'
AND [G1].[DATE] = '2018-11-07'
AND [G2].[DATE] = '2018-11-07'

如果我不包括该代码的最后2行,我将获得5行,将ID的3重复,并将ID重复为4。

想知道是否可以将其更改为:

AND ([G1].[DATE] = '2018-11-07 or [G1].[DATE] Not Exists)

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用以下查询

 SELECT [I].[ID], [I].[DATE], [I].[ITEM], [G1].[PRICE]*[Qty] AS G1Price
       ,[G2].[PRICE]*[Qty] AS G2Price 
 FROM [ITEMS] [I]
 LEFT JOIN [GOODS1] [G1] ON [I].[ITEM] = [G1].[ITEM] AND [I].[DATE]=[G1].[DATE]
 LEFT JOIN [GOODS2] [G2] ON [I].[ITEM] = [G2].[ITEM] AND [I].[DATE]=[G2].[DATE]
 WHERE I.[DATE]= '2018-11-07'