2013-07-24 37 views
0

我有這個麻煩,我只是需要一點點幫助的Sql從項目組合表使包

我有2個表

temp_id uoc description 
305202 AYM HtSeats 
305202 BCM Leather 
305202 BJB Navigation 
305202 BLA PwrSeat 
276722 8 Pwr Driver Seat 
276722 43 Dual Factory Air 
276722 9 w/o Power Windows/Locks 
276722 ADM AlloyWhl 
276722 AMM Cruise 
276722 ATP BackupCam 
276722 BJB Navigation 
276722 BKM PwrLks 
276722 BLA PwrSeat 
276722 BMA PwrWind 
276722 BNP RearAir 

temp_id bbra1 bbra2 bbra3 
305202 AYM BLA 
305202 BCM BLA AYM 
276722 ADM ATP 
276722 BKM BNP BMA 

,我需要把它們結合起來,使這個一個

temp_id uoc description 
305202 AYM/BLA HtSeats/PwrSeat 
305202 BCM/BLA/AYM Leather/PwrSeat/HtSeats 
276722 ADM/ATP AlloyWhl/BackupCam 
276722 BKM/BNP/BMA PwrLks/RearAir/PwrWind 

任何幫助將是不錯謝謝

+0

第一個表'temp_id uoc description'中是否有2或3個字段? – Math

+2

您正在使用哪種RDBMS? SQL Server,MySQL等? –

+0

3字段temp_id uoc描述 – user2615302

回答

1

我明白爲什麼這引起了troubl即解決方案並不完全明顯。下面的查詢使用三個連接,每個連接一個連接。

然後將列連接在一起,注意避免NULL值出現問題。

select t.temp_id, 
     (case when t.bbra3 is not null then concat(t.bbra1, '/', t.bbra2, '/', t.bbra3) 
      when t.bbra2 is not null then concat(t.bbra1, '/', t.bbra2) 
      else t.bbra1 
     end) as uoc, 
     (case when t.bbra3 is not null then concat(t1.description, '/', t2.description, '/', t3.description) 
      when t.bbra2 is not null then concat(t1.description, '/', t2.description) 
      else t1.description 
     end) as description 
from table2 t 
    table1 t1 left outer join 
    on t1.uoc = t.bbra1 and t1.temp_id = t.temp_id left outer join 
    table1 t2 
    on t2.uoc = t.bbra2 and t2.temp_id = t.temp_id left outer join 
    table3 t3 
    on t3.uoc = t.bbra3 and t3.temp_id = t.temp_id; 

此版本始終使用SQL標準。特別是,它使用concat()。但是,並非所有數據庫都使用concat()進行字符串連接,因此您可能需要插入像+||這樣的運算符。

+0

@ user2615302。 。 。我不明白你的評論。描述來自'table1'。有三個連接,每個'bbra'代碼一個連接。然後將它們與uoc進行連接。 –

+0

沒關係,非常感謝你這個工程很棒的坦克 – user2615302