Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

COUNTs of Different Criteria 1

Status
Not open for further replies.

BeeBeeBoy

Programmer
Jul 22, 2006
2
US
Hello,
I have two tables as follows. Each 'User' has a set of related contest entries. The entries can be either a 'video' or an 'image' (MediaType). I want to list the number of videos a user has along with the number of images a user has.

To get just the number of images for instance I can do this:
[tt]SELECT Users.UserID , COUNT(Entries.EntryID) AS NumImages
FROM Users
LEFT JOIN Entries
ON Entries.EntryID=Users.UserID AND Entries.MediaType='Image'
GROUP BY Users.UserID[/tt]

So I would like to take this query and 'merge' it with one like it but with a count of videos as well.


Users:
Code:
UserID  UserName
------------------
 1       Bob
 2       Fred
 3       Joe
Entries:
Code:
EntryID  UserID  MediaType
-----------------------
 1       2       Video
 2       2       Image
 3       1       Image
 4       3       Video
Desired Result:
Code:
UserName  NumVideos  NumImages
-------------------------------
 Bob        0          1
 Fred       1          1
 Joe        1          0

I'm a beginner at SQL. I'm sure there is an elegant solution to this, but I'm not finding it. Many thanks to anyone who can help me with this! :)

 
one method:
Code:
select Users.UserID 
     , ( select count(*)
           from Entries
          where EntryID = Users.UserID 
            and MediaType = 'Video' ) as NumVideos
     , ( select count(*)
           from Entries
          where EntryID = Users.UserID 
            and MediaType = 'Image' ) as NumImages
  from Users

another method:
Code:
select Users.UserID 
     , sum(case when MediaType = 'Video'
                then 1 else 0 end ) as NumVideos
     , sum(case when MediaType = 'Image'
                then 1 else 0 end ) as NumImages
  from Users
left outer
  join Entries
    on Entries.EntryID = Users.UserID

r937.com | rudy.ca
 
Thanks a bunch!

That's exactly what I needed -- and simple and elegant as I figured it would be. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top