PIVOT查询转换为SSRS分组

时间:2015-06-15 07:00:55

标签: sql sql-server reporting-services

如何将以下数据透视查询更改为分组?

    SELECT 
    comb_id
    , [orgunit]
    , [time]
    , [gender]
    , [jobcategory]
    , [ethnicity]
    , [gradegroup]
    , [regiongeo]
    , [emplclass]
    , operatorid
    ,  seq_id
    ,  sequance_name
    , listid 
FROM   
    (SELECT 
        C.comb_id
        , dim_name
        , V.operatorid
        ,V.seq_id
        , V.listid
        , dim_value
        , S.sequance_name 
    FROM   
        gmt_combinationsflat C 
    JOIN 
        gmt_valuesflat V 
    ON 
        C.comb_id = V.comb_id 
    JOIN 
        gmt_rangeseq S 
    ON 
        V.seq_id = S.seq_id 
    JOIN 
        gmt_dimensions D 
    ON 
        C.dim_id = D.dim_id 
    WHERE  
        C.kpi_id = 9 
    AND 
        C.last = 1) AS P 
    PIVOT 
        (Max(dim_value) FOR dim_name IN ( [ORGUNIT ]
                                        , [Time ]
                                        , [Gender ]
                                        , [JobCategory ]
                                        , [Ethnicity ]
                                        , [GradeGroup ]
                                        , [RegionGeo ]
                                        , [EmplClass ] 
                                        ) 
        ) AS pvtt

我尝试过更改为以下内容。但我不确定哪个列应该为群组放置MAX。

select C.comb_id,  [ORGUNIT ], [Time ], [Gender ], [JobCategory ], [Ethnicity ], [GradeGroup ],  [RegionGeo ], [EmplClass ] , operatorid,  seq_id,  sequance_name, listid
FROM   gmt_combinationsflat C 
            JOIN gmt_valuesflat V ON C.comb_id = V.comb_id 
            JOIN gmt_rangeseq S ON V.seq_id = S.seq_id 
            JOIN gmt_dimensions D ON C.dim_id = D.dim_id 
WHERE  C.kpi_id = 9 AND C.last = 1
group by comb_id,[ORGUNIT ], [Time ], [Gender ], [JobCategory ], [Ethnicity ], [GradeGroup ],  [RegionGeo ], [EmplClass ]

1 个答案:

答案 0 :(得分:1)

相当于:

SELECT C.comb_id,
       V.operatorid,
       V.seq_id,
       V.listid,
       S.sequance_name,
       MAX(CASE WHEN dim_name = 'ORGUNIT' THEN dim_value END) AS [orgunit],
       MAX(CASE WHEN dim_name = 'Time' THEN dim_value END) AS [time]
       ....
FROM gmt_combinationsflat C 
JOIN gmt_valuesflat V ON C.comb_id = V.comb_id 
JOIN gmt_rangeseq S ON V.seq_id = S.seq_id 
JOIN gmt_dimensions D ON C.dim_id = D.dim_id 
WHERE C.kpi_id = 9 AND C.last = 1
GROUP BY C.comb_id,
         V.operatorid,
         V.seq_id,
         V.listid,
         S.sequance_name