透视2测量SQL Server

时间:2016-05-19 16:03:25

标签: sql sql-server

更新

我需要做一个最大的AGG_A,但不要用它来转动。

如果我将其保留为维度,如“当前代码”所示,它会产生意外结果(随机行数),因为它实际上是一种度量。

当前代码

Declare @Query_ nvarchar(MAX)
Declare @Cols_For_Pivot_ nvarchar(MAX) 

--Get unique list of metrics in Var_Col for pivot.
SELECT @Cols_For_Pivot_= COALESCE(@Cols_For_Pivot_ + ',','') + QUOTENAME(COL_D)
FROM (SELECT DISTINCT COL_D FROM dbo.my_table) AS PivotTable



SET   @Query_ = 
    N'SELECT COL_A
            ,COL_B
            ,COL_C
            ,AGG_A
            , ' +   @Cols_For_Pivot_ + '
    FROM dbo.min_by_min_static_results
    PIVOT( SUM(AGG_B) 
          FOR COL_D IN (' + @Cols_For_Pivot_ + ')) AS P'


--Execute dynamic query
EXEC sp_executesql @Query_   

期望的结果

SET   @Query_ = 
    N'SELECT COL_A
            ,COL_B
            ,COL_C
            ,MAX(AGG_A) 
            , ' +   @Cols_For_Pivot_ + '
    FROM dbo.min_by_min_static_results
    PIVOT( SUM(AGG_B), 
          FOR COL_D IN (' + @Cols_For_Pivot_ + ')) AS P'

1 个答案:

答案 0 :(得分:0)

知道了,我只需要一个过分区。

SET   @Query_ = 
    N'SELECT COL_A
            ,COL_B
            ,COL_C
            ,MAX(AGG_A) OVER(PARTITION BY 
                                    COL_A
                                   ,COL_B
                                   ,COL_C
                                   , ' +   @Cols_For_Pivot_ + ') AS AGG_A
            , ' +   @Cols_For_Pivot_ + '
    FROM dbo.min_by_min_static_results
    PIVOT( SUM(AGG_B), 
          FOR COL_D IN (' + @Cols_For_Pivot_ + ')) AS P'