sql >> Databasteknik >  >> RDS >> Sqlserver

Dynamiska konverteringsrader till kolumner SQL

Du kan uppnå detta genom att köra en dynamisk sql-fråga.

Fråga

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);



  1. SubSonic 3 och MySQL, att ta bort understreck från kolumnnamnet i metoden CleanUp() orsakar undantag när egenskapen används i linq-query

  2. Doktrin 2-mappning som refererar till unik nyckel

  3. MySQL - Ta bort standardvärdet för Datetime-fältet

  4. Hur man jämför numeriska värden i samma kolumner för flera kolumner med Oracle SQL