Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL Sum Query with IF Condition

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.

Here is the query:

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 

This query works just fine.

When I try to add the below conditional SUM statement:

 SUM('TotalAmount'(PaymentType = "credit card", 1,0)) AS CreditCardTotal, 

This conditional IF statement fails out.

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.

like image 827
Matthew Colley Avatar asked Jan 04 '12 18:01

Matthew Colley


People also ask

Can we use sum with where clause?

SQL SUM() with where clause We can selectively find the sum of only those rows, which satisfy the given condition. To do this, we can use the where clause in the SQL statement.

How can I sum two columns in MySQL?

Example: MySQL SUM() function using multiple columnsMySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .

How do I total a column in MySQL?

You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.


1 Answers

Try with a CASE in this way :

SUM(CASE      WHEN PaymentType = "credit card"      THEN TotalAmount      ELSE 0  END) AS CreditCardTotal, 

Should give what you are looking for ...

like image 65
aleroot Avatar answered Sep 21 '22 12:09

aleroot