MYSQL Sum Query with IF Condition(带有IF条件的MYSQL求和查询)
问题描述
我正在为 SUM 上具有多个 IF 条件的报表构建查询.我在 SUM 上遇到多个 IF 条件的问题.
I am building a query for a report with multiple IF conditions on the SUM. I am having problems with a multiple IF conditions on the SUM.
这里是查询:
SELECT SUM(`totalamount`) AS Total,
SUM(`PayPalFee`) AS Fees,
DATE(`TransactionDate`) AS `Day`,
SUM(IF(PaymentType = "paypal", 1,0)) AS Paypal,
SUM(IF(PaymentType = "check", 1,0)) AS Checks,
SUM(IF(PaymentType = "credit card", 1,0)) AS CreditCard,
COUNT(*) AS Entries
FROM my_table
WHERE TransactionDate between '2011-05-05' AND '2012-01-30'
GROUP BY day
ORDER BY `day` ASC
这个查询工作得很好.
当我尝试添加以下条件 SUM 语句时:
When I try to add the below conditional SUM statement:
SUM('TotalAmount'(PaymentType = "credit card", 1,0)) AS CreditCardTotal,
此条件 IF 语句失败.
This conditional IF statement fails out.
我有一个名为TotalAmount"的列和一个名为PaymentType"的列我希望创建每天信用卡交易的总和、每天支票交易的总和、贝宝交易的总和每天,.我试图创建一个子查询,但这会返回整个 TotalAmount 列的值,而不是按天细分.
I have a column called 'TotalAmount' and a column called 'PaymentType' I am looking to create a SUM of the credit card transactions by each day, a SUM of the checks transactions by each day, a SUM of the paypal transactions by each day,. I have tried to create a subquery but this returns a value for the entire TotalAmount column, not broken down by day.
推荐答案
试试 CASE 这样:
SUM(CASE
WHEN PaymentType = "credit card"
THEN TotalAmount
ELSE 0
END) AS CreditCardTotal,
应该给你正在寻找的东西......
Should give what you are looking for ...
这篇关于带有IF条件的MYSQL求和查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有IF条件的MYSQL求和查询


基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01