Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2010
    Posts
    9

    Unanswered: Tricky SELECT Statement

    I'm just hoping that someone might be able to help me out with a tricky SELECT statement that I can't get my head around.

    I have two tables - one that contains SERVER items, and another that contains performance ALERTS for those servers.

    Here are some relevant fields:

    SERVERS (table)
    serverid
    accountid
    servername

    ALERTS (table)
    alertid
    serverid
    alerttext

    I need to write a SELECT statement that gives me all of the servers for a particular account. e.g.

    SELECT serverid, servername FROM servers WHERE accountid=123

    and also a COUNT of the number of alerts that each server currently has.

    So, the end result might look something like this:

    serverid servername numalerts
    0 svr01 0
    1 svr02 3
    2 svr03 1
    3 svr04 0

    Can anyone help out with that?

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    this is not tricky at all
    Code:
    SELECT servers.serverid
         , servers.servername 
         , COUNT(alerts.serverid) AS numalerts
      FROM servers 
    LEFT OUTER
      JOIN alerts
        ON alerts.serverid = servers.serverid
     WHERE servers.accountid = 123
    GROUP
        BY servers.serverid
    your basic left outer join count query

    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

  3. #3
    Join Date
    Jan 2010
    Posts
    9
    You're a life-saver. Been struggling with that for hours! Thanks so much for the help.

Posting Permissions

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