Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Conversione dinamica di righe in colonne SQL

Puoi ottenere ciò eseguendo una query sql dinamica.

Richiesta

declare @sql nvarchar(max);

select @sql = 'select [Card], ' + stuff((
        select distinct 
        ',min(case [sl_no] when ' + cast([sl_no] as varchar(100)) 
        + ' then [TranID] end) as [TranID_' + cast([sl_no] as varchar(100)) + ']' +
        ',min(case [sl_no] when ' + cast([sl_no] as varchar(100)) 
        + ' then [Date] end) as [Date_' + cast([sl_no] as varchar(100)) + ']' +
        ',min(case [sl_no] when ' + cast([sl_no] as varchar(100)) 
        + ' then [ShopType] end) as [ShopType_' + cast([sl_no] as varchar(100)) + ']' +
        ',min(case [sl_no] when ' + cast([sl_no] as varchar(100)) 
        + ' then [ShopName] end) as [ShopName_' + cast([sl_no] as varchar(100)) + ']' 
        from (
            select [sl_no] = row_number() over(
                partition by [Card] 
                order by [Date]
            ), * from [dbo].[tbl_name]
        ) as [t]
        for xml path('')
    )
    , 1, 1, ''
);

set @sql += ' from (select [sl_no] = row_number() over(partition by [Card] order by [Date]), 
            * from [dbo].[tbl_name]) as [t] group by [Card];';

exec(@sql);