简体   繁体   中英

How to add 'total' row at bottom of table in SQL?

I have a pivot table with a totals column but am having trouble making a totals row at the bottom of the table using SQL. This is the code I currently have:

SELECT
    Committee,
    COUNT(CASE WHEN status = 'Resume Review'    THEN 1 END) AS "Resume Review",
    COUNT(CASE WHEN status = 'Interviewing'     THEN 1 END) AS "Interviewing",
    COUNT(CASE WHEN status = 'Coding Challenge' THEN 1 END) AS "Coding Challenge",
    COUNT(*) AS Total
FROM EMPLOYEES
WHERE status IN ('Resume Review', 'Interviewing', 'Coding Challenge')
GROUP BY Committee;

which gives this:

Committee   Resume Review   Interviewing    Take Home Challenge  Total 
UI/UX              3             2                  1              6
Finance            0             2                  2              4
Marketing          2             4                  1              7
          

I am trying to achieve this:

Committee   Resume Review   Interviewing    Take Home Challenge  Total 
UI/UX              3             2                  1              6
Finance            0             2                  2              4
Marketing          2             4                  1              7
Total              5             8                  4              17

Thanks in advance: :)

You can add 'ROLLUP' to 'GROUP BY'

SELECT
    CASE WHEN GROUPING(Committee) = 1 THEN 'Total' ELSE Committee END AS Committee,
    COUNT(CASE WHEN status = 'Resume Review'    THEN 1 END) AS "Resume Review",
    COUNT(CASE WHEN status = 'Interviewing'     THEN 1 END) AS "Interviewing",
    COUNT(CASE WHEN status = 'Coding Challenge' THEN 1 END) AS "Coding Challenge",
    COUNT(*) AS Total
FROM EMPLOYEES
WHERE status IN ('Resume Review', 'Interviewing', 'Coding Challenge')
GROUP BY Committee WITH ROLLUP

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM