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

複数の列を持つSQLServer動的ピボット

    ストアドプロシージャを使用しない、より詳細な動的SQLクエリは次のとおりです。

    DECLARE @cols AS NVARCHAR(MAX);
    DECLARE @pivotSales AS NVARCHAR(MAX);
    DECLARE @sql AS NVARCHAR(MAX);
    
    SELECT @cols = ISNULL(@cols + ', ', '') + QUOTENAME(Country)
    FROM (SELECT DISTINCT Country FROM tbl1) AS Countries
    
    SET @pivotSales = N'SELECT IssuedOn, ' + @cols +'
    FROM (SELECT IssuedOn, Country, Sales FROM tbl1) AS sales
    PIVOT(SUM(Sales) FOR Country IN (' + @cols + ')) AS pvt';
    
    SET @sql = ';WITH CTE_SalesPivot AS (
    '[email protected]+'
    ),
    CTE_SalesTotal AS (
      SELECT IssuedOn, SUM(Sales) AS [Grand Total]
      FROM tbl1
      GROUP BY IssuedOn
    ),
    CTE_Transactions AS (
      SELECT IssuedOn, SUM(Transactions) AS [Transaction Count]
      FROM tbl1
      GROUP BY IssuedOn
    )
    SELECT CTE_SalesPivot.IssuedOn, ' + @cols + ', CTE_SalesTotal.[Grand Total], CTE_Transactions.[Transaction Count]
    FROM
    CTE_SalesPivot
    INNER JOIN CTE_SalesTotal ON CTE_SalesPivot.IssuedOn = CTE_SalesTotal.IssuedOn
    INNER JOIN CTE_Transactions ON CTE_SalesPivot.IssuedOn = CTE_Transactions.IssuedOn';
    
    EXEC sp_executesql @sql;
    



    1. SQLServerのパフォーマンスのボトルネックについて話す

    2. ORACLEでパーティションテーブルの名前が自動的に変更されます

    3. 2016年に登場するOracle12.2.0.1

    4. Amazon RelationalDatabaseServiceのメリットとセキュリティ