mysql查询行中的sum值

时间:2017-02-28 23:11:12

标签: mysql sql

是否可以对此查询中的单个行的值求和? 我已经大胆提出了我的想法,但它没有用。

SELECT 
    `view_monthly_bills`.`pay_id` AS `pay_id`,
    `view_monthly_bills`.`pay_month` AS `pay_month`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'Mortgage') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `Mortgage`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'Shopping') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `Shopping`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'TV') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `TV`,
        **SUM( Mortgage + Shopping + TV)**
FROM
    `view_monthly_bills`
GROUP BY `view_monthly_bills`.`pay_id` , `view_monthly_bills`.`pay_month`
ORDER BY `view_monthly_bills`.`pay_id` DESC
LIMIT 6

1 个答案:

答案 0 :(得分:0)

尝试使用case语句OR和函数agregation SUM

SELECT 
    `view_monthly_bills`.`pay_id` AS `pay_id`,
    `view_monthly_bills`.`pay_month` AS `pay_month`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'Mortgage') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `Mortgage`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'Shopping') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `Shopping`,
    GROUP_CONCAT((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'TV') THEN `view_monthly_bills`.`debit`
            ELSE NULL
        END)
        SEPARATOR ',') AS `TV`,
        SUM((CASE
            WHEN (`view_monthly_bills`.`bill_type` = 'TV' OR
                `view_monthly_bills`.`bill_type` = 'Shopping' OR
                `view_monthly_bills`.`bill_type` = 'Mortgage'
                )THEN `view_monthly_bills`.`debit`
            ELSE 0
        END)) as sum_debit
FROM
    `view_monthly_bills`
GROUP BY `view_monthly_bills`.`pay_id` , `view_monthly_bills`.`pay_month`
ORDER BY `view_monthly_bills`.`pay_id` DESC
LIMIT 6