Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2009-07-12
3
Medium Priority
?
1,887 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 25

Expert Comment

by:lwadwell
ID: 24836713
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 2000 total points
ID: 24836779
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
ID: 31602678
Thanks so much.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I’ll talk about multi-threaded slave statistics printed in MySQL error log file.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

650 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