sql >> データベース >  >> RDS >> Sqlserver

行から列への動的変換 SQL

    これは、動的 SQL クエリを実行することで実現できます。

    クエリ

    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. Oracleの日付

    2. テーブル名である変数から選択する方法nPostgre>=9.2

    3. SQLServerのテーブルを参照するオブジェクトを特定する

    4. 各ステートメントのトリガーの例