I would like to combine ROLLUP with PIVOT - is that an option?

荒凉一梦 提交于 2019-12-03 17:26:26

You didn't post the table schema, so I tried to infer it. I started with the input you gave (see the comment in the innermost SELECT), so you should be able to adapt this to your actual schema. I included an extra author without any documents, because I figured you'd want to see those in the final report output. It's trivial to exclude those authors.

DECLARE @Status table
(
    Id int NOT NULL,
    Status nvarchar(50) NOT NULL
)

DECLARE @Authors table
(
    Id int NOT NULL,
    Name nvarchar(50) NOT NULL
)

DECLARE @Documents table
(
    Id int NOT NULL,
    AuthorId int NOT NULL,
    StatusId int NOT NULL
)

INSERT INTO @Status VALUES (1, 'Duplicate')
INSERT INTO @Status VALUES (2, 'Failure')
INSERT INTO @Status VALUES (3, 'Rejected')
INSERT INTO @Status VALUES (4, 'Success')

INSERT INTO @Authors VALUES (1, 'Alan')
INSERT INTO @Authors VALUES (2, 'Bob')
INSERT INTO @Authors VALUES (3, 'Charles')
INSERT INTO @Authors VALUES (4, 'Dave')
INSERT INTO @Authors VALUES (5, 'Tom') -- Test for authors without documents

INSERT INTO @Documents VALUES (1, 1, 4)
INSERT INTO @Documents VALUES (2, 2, 2)
INSERT INTO @Documents VALUES (3, 2, 4)
INSERT INTO @Documents VALUES (4, 3, 4)
INSERT INTO @Documents VALUES (5, 4, 2)
INSERT INTO @Documents VALUES (6, 4, 1)

SELECT
    (CASE WHEN GROUPING(Name) = 1 THEN 'Total' ELSE Name END) AS Author,
    SUM(Duplicate) AS Duplicate,
    SUM(Failure) AS Failure,
    SUM(Rejected) AS Rejected,
    SUM(Success) AS Success,
    SUM(Duplicate + Failure + Rejected + Success) AS Total
    FROM
    (
        SELECT
            Name,
            (CASE WHEN Status = 'Duplicate' THEN 1 ELSE 0 END) AS Duplicate,
            (CASE WHEN Status = 'Failure' THEN 1 ELSE 0 END) AS Failure,
            (CASE WHEN Status = 'Rejected' THEN 1 ELSE 0 END) AS Rejected,
            (CASE WHEN Status = 'Success' THEN 1 ELSE 0 END) AS Success
            FROM
            (
                -- Original input
                SELECT
                    a.Name,
                    s.Status
                    FROM @Authors a
                    LEFT OUTER JOIN @Documents d ON d.AuthorId = a.Id
                    LEFT OUTER JOIN @Status s ON d.StatusId = s.Id
            ) i
    ) j
    GROUP BY Name WITH ROLLUP

Output:

Author   Duplicate  Failure  Rejected  Success  Total
Alan     0          0        0         1        1
Bob      0          1        0         1        2
Charles  0          0        0         1        1
Dave     1          1        0         0        2
Tom      0          0        0         0        0
Total    1          2        0         3        6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!