0

我遇到了这个问题,我只需要一点帮助

我有 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

任何帮助都会很好谢谢

4

1 回答 1

1

我明白为什么这会引起麻烦。解决方案并不完全显而易见。下面的查询使用三个连接,每列一个。

然后它将列连接在一起,注意避免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()用于字符串连接,因此您可能需要添加类似+or的运算符||

于 2013-07-24T15:49:13.520 回答