SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    Sheffield
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question How to include zero counts

    In a query like:

    SELECT a.id, COUNT(*)
    FROM a, b
    WHERE a.id=b.id
    GROUP BY id

    how does one include rows for id's that have a count of zero?

    N51

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,022
    Mentioned
    53 Post(s)
    Tagged
    2 Thread(s)
    Code:
    select a.id
         , count(b.id) as bees
      from a
    left outer
      join b
        on a.id = b.id
    group 
        by a.id
    r937.com | rudy.ca | Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    Chessplayer kleineme's Avatar
    Join Date
    Apr 2004
    Location
    Germany
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Code:
    SELECT a.id, COUNT(*)
    FROM a LEFT JOIN b
    ON a.id = b.id
    GROUP BY a.id;
    Edit:


    ok, I'm too slow and too dumb
    it sure has to be count(b.id) because else you will get a count of one even when there's none
    Never ascribe to malice,
    that which can be explained by incompetence.
    Your code should not look unmaintainable, just be that way.

  4. #4
    SitePoint Enthusiast
    Join Date
    Nov 2004
    Location
    Sheffield
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys, that's a big help!

    N51


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •