2016-09-27 39 views
0

我有一個問題鏈接兩個表,其中需要多次連接1個字段。加入兩個SQL表,其中一個連接字段被多次使用

兩個表如下:

Venue_Location_Master

  • ID
  • LOCATION_NAME
  • UNID
  • is_warehouse

Bag_Dim

  • EVENT_ID
  • Bag_type
  • bag_id
  • label_id
  • CREATED_DATE
  • created_by_employee
  • origin_location_id
  • destination_location_id
  • composition_id

該表的連接origin_location_id或destination_location_id到Venue_Location_Master.id

我試圖構建一個返回查詢:

  • bag_id
  • created_by_employee
  • event_name
  • origin_location_id
  • Venue_Location_Master.location_name(ORIGIN_NAME)
  • destination_location_id
  • Venue_Location_Master.location_name(DESTINATION_NAME)

我用工會試過,但返回所需的數據,而是跨越兩行(見下文)。任何人有任何建議?

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' 
+1

左對齊SQL很難閱讀。 – jarlh

+0

您想要將兩列合併爲一個列值(s)? –

+0

這個想法是爲origin_location_id和destination_location_id返回一個帶venue_location_master.location_name的行。我猜這可能需要給列提供一個別名來區分它們? – Sarah

回答

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' 
+0

完美。謝謝。這是給連接表一個別名,我不能得到我的頭! – Sarah

相關問題