If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > Count based on two different states for same field

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 05-31-10, 04:15
datune datune is offline
Registered User
 
Join Date: Jan 2004
Posts: 6
Count based on two different states for same field

Hello,

if I have one table, with two fields, storeid and printed, and I want to select a count of all records grouped by storeid where printed=0 BUT would also like to have the count of all records per storeid where printed=1

Can this be done in a single query?

Example table:

Code:
id      storeid     printed
1           3           0
2           3           1
3           3           1
4           3           1
5           3           0
6           6           0
7           6           1
8           6           1
Expected result:
Code:
storeid     count_printed   count_not_printed
    3           3                   2
    6           2                   1
Reply With Quote
  #2 (permalink)  
Old 05-31-10, 07:16
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Code:
SELECT storeid
     , COUNT(CASE WHEN printed = 1
                  THEN 'humpty' 
                  ELSE NULL END) AS count_printed
     , COUNT(CASE WHEN printed = 0
                  THEN 'dumpty' 
                  ELSE NULL END) AS count_not_printed
  FROM daTable
GROUP
    BY storeid
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 05-31-10, 14:05
Pat Phelan Pat Phelan is offline
Resident Curmudgeon
 
Join Date: Feb 2004
Location: In front of the computer
Posts: 12,606
Code:
SELECT storeid, printed, Count(*)
   FROM daTable
   GROUP BY storeid, printed
-PatP
__________________
In theory, theory and practice are identical. In practice, theory and practice are unrelated.
Reply With Quote
  #4 (permalink)  
Old 06-01-10, 01:28
datune datune is offline
Registered User
 
Join Date: Jan 2004
Posts: 6
@r937

Thanks a lot, that is exactly what I was looking for. Even though I have been working with MySQL for over ten years, I never had this case before, and I never would have thought of what you did. Much appreciated!
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On