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
Solved

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

Posted on 2009-07-12
3
1,810 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
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 500 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
When it comes to protecting Oracle Database servers and systems, there are a ton of myths out there. Here are the most common.
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…

809 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