需要通用转置脚本

时间:2019-05-17 10:28:15

标签: sql pivot transpose

enter image description here

以下是特定交易ID的表格

TransactionId FirstName Lastname ContactNo ....
    27           John      A        123
    27           Mark      B        124 

我需要像

TransactionId FirstName Lastname ContactNo FirstName Lastname ContactNo ....
   27           John       A        123       Mark      B        124

1 个答案:

答案 0 :(得分:0)

SELECT @col_list = Stuff((SELECT ',id = max(case when id = '
                             + Cast(id AS VARCHAR(50))
                             + ' then id end), mobilenumber = max(case when id = '
                             + Cast(id AS VARCHAR(50))
                             + ' then mobilenumber  end)'                                
                      FROM   [dbo].[TransactionContact] where  transactionid in (137103,137102)

                      ORDER  BY id
                      FOR xml path('')), 1, 1, '')

EXEC('从[dbo]中选择'+ @ col_list +'。[TransactionContact]')

此操作如上所述,但是为同一行而不是不同行中的所有transactionid带来了联系