gpt4 book ai didi

mysql - mysql查询行中的总和值

转载 作者:行者123 更新时间:2023-11-29 19:19:32 25 4
gpt4 key购买 nike

是否可以将此查询中各行的值相加?我大胆地提出了自己的想法,但行不通。

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

最佳答案

尝试使用case语句与OR和函数聚合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

关于mysql - mysql查询行中的总和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com