有没有办法包括所有案例的总和?

时间:2018-07-28 03:50:17

标签: mysql

给出SQL:是否可以引入结果集的总数?

SELECT 
    SUM(CASE
        WHEN status = 3 THEN 1
        ELSE 0
    END) AS Open,
    SUM(CASE
        WHEN status = 4 THEN 1
        ELSE 0
    END) AS Close
FROM
    Table1
WHERE
    id = 2;

结果:

Open,Close
5,5

所需结果:

Open,Close,Total
5,5,10

3 个答案:

答案 0 :(得分:3)

只需添加另一个案例声明

SELECT 
    SUM(CASE
        WHEN status = 3 THEN 1
        ELSE 0
    END) AS Open,
    SUM(CASE
        WHEN status = 4 THEN 1
        ELSE 0
    END) AS Close
    SUM(CASE
        WHEN status IN (3, 4) THEN 1
        ELSE 0
    END) AS Total
FROM
    Table1
WHERE
    id = 2;

答案 1 :(得分:1)

您可以使用CTE:

WITH sumCase AS (
SELECT 
    SUM(CASE
        WHEN status = 3 THEN 1
        ELSE 0
    END) AS Open,
    SUM(CASE
        WHEN status = 4 THEN 1
        ELSE 0
    END) AS Close
FROM
    Table1
WHERE
    id = 2;)
SELECT Open,Close, Open + Close AS Total FROM Table1;

http://www.mysqltutorial.org/mysql-cte/

答案 2 :(得分:0)

使用子查询

   select open,close,open+close as total from
    (
       SELECT 
        SUM(CASE  WHEN status = 3 THEN 1
             ELSE 0
             END ) AS Open,
       SUM(CASE   WHEN status = 4 THEN 1
           ELSE 0
           END) AS Close
    FROM
    Table1
    WHERE   id = 2   ) as T