Solved

Can I use SQL (MySQL) to get result like sumif?

Posted on 2009-07-12
3
1,789 Views
Last Modified: 2012-05-07
I know the usage of count and group by like "SELECT customer_id, COUNT(product_type) as sales_count FROM sales GROUP BY customer_id, product_type";
*******************
Result:
customer_id            sales_count
1001                  4
1002                  8
...

My question is: The value of product_type must be 1, 2, 3 or 4, can I use one sql to get count of each type?

I want result like:
customer_id            type_1      type_2      type_3      type_4
1001                  2            1            1            0
1002                  3            0            4            1
...
0
Comment
Question by:yauhing
3 Comments
 
LVL 25

Expert Comment

by:lwadwell
Comment Utility
Hi yauhing,

try using a CASE statement inside a SUM ...

SELECT customer_id, SUM(CASE when product_type = 1 then 1 else 0 end) as type_1
FROM sales
GROUP BY customer_id

lwadwell
0
 
LVL 33

Accepted Solution

by:
snoyes_jw earned 500 total points
Comment Utility
No need for the CASE - since the euqal operator returns 1 or 0, you can sum that directly:

SELECT
  customer_id,
  SUM(product_type = 1) AS type_1,
  SUM(product_type = 2) AS type_2...
0
 
LVL 5

Author Closing Comment

by:yauhing
Comment Utility
Thanks so much.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now