我在连接两个表时遇到问题,其中多次需要1个连接字段。
这两个表格如下:
Venue_Location_Master
Bag_Dim
这些表在origin_location_id或destination_location_id上加入Venue_Location_Master.id
我正在尝试构造一个返回的查询:
我尝试过使用union,但是会返回所需的数据,但会跨两行(见下文)。有人有什么建议吗?
SELECT [bag_id],
[created_date],
[created_by_employee],
[origin_location_id],
ISNULL([venue_location_master].[location_name], 'NULL') AS [origin_location_name],
[destination_location_id],
ISNULL([venue_location_master].[location_name], 'NULL') AS [destination_location_name]
,ISNULL([event_master].[event_name], 'NULL') AS [event_name]
FROM [variance_cash].[dbo].[Bag_Dim]
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master]
ON [Bag_Dim].[destination_location_id] = [venue_location_master].[id]
LEFT JOIN [verteda_rts_v4].[dbo].[event_master]
ON [Bag_Dim].[event_id] = [event_master].[id]
WHERE [bag_id] = 'K5334'
答案 0 :(得分:0)
如果您使用别名,则可以在同一个表上连接两次。
只需加入正确的字段,这应该可以解决问题。
SELECT
[bag_id],
[created_date],
[created_by_employee],
--origin
[origin_location_id],
--use table alias to get correct origin name
ISNULL(origin.[location_name], 'NULL') AS [origin_name],
--destination
[destination_location_id],
--use table alias to get correct destination name
ISNULL(destination.[location_name], 'NULL') AS [destination_name],
ISNULL([event_master].[event_name], 'NULL') AS [event_name]
FROM [variance_cash].[dbo].[Bag_Dim]
--join on destination, alias is... destination
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master] as destination
ON [Bag_Dim].[destination_location_id] = destination.[id]
--join on origin, alias is... origin
LEFT JOIN [verteda_rts_v4].[dbo].[venue_location_master] as origin
ON [Bag_Dim].[origin_location_id] = origin.[id]
LEFT JOIN [verteda_rts_v4].[dbo].[event_master]
ON [Bag_Dim].[event_id] = [event_master].[id]
WHERE [bag_id] = 'K5334'