SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Dec 2003
    Location
    Estonia
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    SQL query help: multiple rules

    PostgreSQL
    I have problems with the following situation. Can this even be done in one query?

    I have 3 tables - 'results_of_game' and (less important) 'games' and 'players'.
    'results_of_game' table has fields 'game_id', 'player_id', 'position', 'result'.

    Now comes the problem:
    I want to find all game_id's where:
    * player in first position (results_of_game.position=1) has result='A'
    AND
    * player in second position has result='B'
    AND
    * all the remaining players have result='C'

    (A/B/C are 3 different numeric values). Number of players in every game is an unknown number between 3 and 10 (and if it makes things any easier then table 'games' includes 'number_of_players' field). How to receive list of game_id's that fulfill these requirements?

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,341
    Mentioned
    63 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT game_id
      FROM results_of_game 
    GROUP
        BY game_id
    HAVING SUM(CASE WHEN position = 1
                     AND result = 'A'
                    THEN 1 ELSE 0 END) = 1
       AND SUM(CASE WHEN position = 2
                     AND result = 'B'
                    THEN 1 ELSE 0 END) = 1
       AND SUM(CASE WHEN position > 2
                     AND result <> = 'C'
                    THEN 1 ELSE 0 END) < 1
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Member
    Join Date
    Dec 2003
    Location
    Estonia
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, this is exactly what I needed. Thank you


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
  •