从所选列中计算总数

时间:2019-04-16 09:34:29

标签: mysql

我正在尝试检索结果每一列的总数。下面是我的预期结果和菜单选择表。

菜单选择表:

Menu selection table

查询/预期结果后:

Expected result

问题是我在计算每一列的总数时遇到问题。

这是我的查询:


    SELECT menu_option,
        SUM(IF(callStatus='QUEUE', 1, 0)) AS Queue,
        SUM(IF(callStatus='ROUTING' , 1, 0)) AS Routing,
        SUM(IF(callStatus='CALLBACK' , 1, 0)) AS Callback,
        SUM(IF(callStatus='ANSWER' , 1, 0)) AS Answer
    FROM tbl_call_center_menu_selection
    GROUP BY menu_option
    UNION
    SELECT  'Total' AS c, 5 AS a, 2 AS b, 0 AS c, 0 AS d
    FROM tbl_call_center_menu_selection

1 个答案:

答案 0 :(得分:0)

您可以尝试使用子查询

SELECT menu_option,
        SUM(IF(callStatus='QUEUE', 1, 0)) AS Queue,
        SUM(IF(callStatus='ROUTING' , 1, 0)) AS Routing,
        SUM(IF(callStatus='CALLBACK' , 1, 0)) AS Callback,
        SUM(IF(callStatus='ANSWER' , 1, 0)) AS Answer
    FROM tbl_call_center_menu_selection
    GROUP BY menu_option
    UNION
    SELECT  'Total' , sum(Queue), sum(Routing), sum(Callback), sum(Answer)
    FROM 
    (
        select menu_option,
        SUM(IF(callStatus='QUEUE', 1, 0)) AS Queue,
        SUM(IF(callStatus='ROUTING' , 1, 0)) AS Routing,
        SUM(IF(callStatus='CALLBACK' , 1, 0)) AS Callback,
        SUM(IF(callStatus='ANSWER' , 1, 0)) AS Answer
    FROM tbl_call_center_menu_selection group by menu_option
    )A