如何在语言列上执行ROLLUP并获取一行TOTAL作为最后一行?

时间:2017-08-16 15:22:09

标签: sql sql-server stored-procedures rollup

我想在语言列上执行ROLLUP并将最后一行生成为Total。
我不知道在哪里放ROLLUP 对于Eg:

AS
        BEGIN
            declare @sqlCommand NVARCHAR(4000) =
            'SELECT Language, col2, col3, col4, Total = col2 + col3 + col4
            FROM (  SELECT xL.lN, xS.sN, UC.UC
                    FROM (UC LEFT JOIN xL ON UC.Language = xL.xL) LEFT JOIN xS
                    ON UC.ssn = xS.ssn
                    WHERE
                        ((DS BETWEEN .... AND ....) AND
                        (HS BETWEEN .... AND ....) AND
                        (MS BETWEEN .... AND ....))) UCs
                        PIVOT (SUM (UC) for sN IN
                        (col2, col3, col4))
                        AS PVT;';
        EXEC SP_EXECUTESQL @sqlCommand
        END

3 个答案:

答案 0 :(得分:0)

汇总已使用Group by..完成,如果您必须在此处应用组,则需要按所选列的所有列进行分组。

答案 1 :(得分:0)

您可以尝试分组。

With result as (
    SELECT Language, col2, col3, col4, Total = col2 + col3 + col4
    FROM (  SELECT xL.lN, xS.sN, UC.UC
            FROM (UC LEFT JOIN xL ON UC.Language = xL.xL) LEFT JOIN xS
            ON UC.ssn = xS.ssn
            WHERE
            ((DS BETWEEN .... AND ....) AND
            (HS BETWEEN .... AND ....) AND
            (MS BETWEEN .... AND ....))
    ) UCs
    PIVOT (SUM (UC) for sN 
        IN (col2, col3, col4)
    ) AS PVT
)
SELECT Language, col2, col3, col4, sum(Total) as Total
FROM result
GROUP BY GROUPING SETS((Language, col2, col3, col4), ())

答案 2 :(得分:0)

如果您尝试使用每列的总和来获取行总数,则可以尝试以下查询:

- 方法1:

With result as (
    SELECT Language, col2, col3, col4, Total = col2 + col3 + col4
    FROM (  SELECT xL.lN, xS.sN, UC.UC
            FROM (UC LEFT JOIN xL ON UC.Language = xL.xL) LEFT JOIN xS
            ON UC.ssn = xS.ssn
            WHERE
            ((DS BETWEEN .... AND ....) AND
            (HS BETWEEN .... AND ....) AND
            (MS BETWEEN .... AND ....))
    ) UCs
    PIVOT (SUM (UC) for sN 
        IN (col2, col3, col4)
    ) AS PVT
)
SELECT Language, col2, col3, col4, sum(Total) as Total
FROM result
UNION ALL
SELECT 'TOTAL', sum(col2) as col2, sum(col3) as col3, cum(col4) as col4, sum(Total) as Total
FROM result

- 方法2:

With result as (
    SELECT Language, col2, col3, col4, Total = col2 + col3 + col4
    FROM (  SELECT xL.lN, xS.sN, UC.UC
            FROM (UC LEFT JOIN xL ON UC.Language = xL.xL) LEFT JOIN xS
            ON UC.ssn = xS.ssn
            WHERE
            ((DS BETWEEN .... AND ....) AND
            (HS BETWEEN .... AND ....) AND
            (MS BETWEEN .... AND ....))
    ) UCs
    PIVOT (SUM (UC) for sN 
        IN (col2, col3, col4)
    ) AS PVT
)
SELECT case when grouping(Language) = 1 then 'Total' else Language end as Language
, sum(col2) as col2
, sum(col3) as col3
, sum(col4) as col4
, sum(Total) as Total
from result
group by Language with Rollup
order by grouping(Language)