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 of two values in a joined table?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-04-10, 08:16
Spudhead Spudhead is offline
Registered User
 
Join Date: Jan 2002
Posts: 189
count of two values in a joined table?

I'm not sure what I need to do here. I think it's probably simple, but my brain's stopped working.

With the following two tables:

tblBasket
idBasket INT PK
basketDate date

tblBasketContents
idBasketContents INT PK
idBasket INT FK
isFree BIT

I want to generate a query that shows a list of tblBasket entries.

Each row in the query resultset should show the basket date, a count of items in that Basket where isFree is 1, and a count of items where isFree is 0.

Do I have to join the table to itself, or does it involve some sort of case statement, or is there another answer?
Reply With Quote
  #2 (permalink)  
Old 01-04-10, 08:32
r937 r937 is offline
SQL Consultant
 
Join Date: Apr 2002
Location: Toronto, Canada
Posts: 19,525
Code:
SELECT b.idBasket
     , b.basketDate
     , COUNT(CASE WHEN bc.isFree = 0 THEN 'count me' END) AS not_free
     , COUNT(CASE WHEN bc.isFree = 1 THEN 'no, count me' END) AS free
  FROM tblBasket AS b
LEFT OUTER
  JOIN tblBasketContents AS bc
    ON bc.idBasket = b.idBasket
GROUP
    BY b.idBasket
__________________
r937.com | rudy.ca
please visit Simply SQL and buy my book
Reply With Quote
  #3 (permalink)  
Old 01-04-10, 09:56
Spudhead Spudhead is offline
Registered User
 
Join Date: Jan 2002
Posts: 189
That's the one - thank you
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