使用SQL将一个表中的两行组合为单行

时间:2013-01-02 04:31:45

标签: sql-server

ID  Name    Address Acc_Number  BookingNo   Amt
 1  MERY    Kollam  111111111   NULL        1000
 2  Jos     Kochi   111111111   c/01        NULL

输出

ID  Name    Address Acc_Number  BookingNo   Amt
1   MERY    Kollam  111111111   c/01        1000

2 个答案:

答案 0 :(得分:2)

我认为使用Acc_Number自动加入同一个表应该实现

SELECT 
     a.ID,  
     a.Name,    
     a.Address, 
     a.Acc_Number,  
     COALESCE(a.BookingNo, b.BookingNo) as BookingNo,   
     COALESCE(a.Amt, b.Amt) As Amt
FROM TableA a
JOIN TableA b
     ON a.Acc_Number = b.Acc_Number

答案 1 :(得分:0)

SELECT top 1 t1.ID,t1.Name,  
     t1.Address, 
     t1.Acc_Number,  
     COALESCE(t1.BookingNo, t2.BookingNo) as 'BookingNo',COALESCE(t1.Amt, t2.Amt) as 'Amt'
FROM testtable1 t1 JOIN testtable1 t2 
     ON t1.Acc_Number = t2.Acc_Number and t1.NAME!=t2.NAME