sql >> Database teknologi >  >> RDS >> PostgreSQL

Har problemer med at kombinere HAVING med WHERE på en meget enkel QUERY

Jeg har ikke nogen PostgreSQL-baggrund, men lad os se, om dette virker:

Jeg vil starte dette med at forenkle det ved at skrive en forespørgsel, der først returnerer den samlede score efter spiller:

SELECT player_id, SUM(score) score
FROM (
  SELECT first_player as player_id, first_score as score
  FROM matches
  UNION ALL
  SELECT second_player, second_score
  FROM matches
)
GROUP BY player_id

Tilslut nu dette datasæt til spillere for at finde grupperne:

SELECT w.player_id, p.group_id, w.score
FROM
(
  SELECT player_id, SUM(score) score
  FROM (
    SELECT first_player as player_id, first_score as score
    FROM matches
    UNION ALL
    SELECT second_player, second_score
    FROM matches
  )
  GROUP BY player_id
) as w
inner join players p
on p.player_id = w.player_id

Nu har vi alle spillere, deres samlede score og deres gruppe. Vil vi identificere vinderen efter gruppe? Vi kan bruge rangering funktioner til at gøre dette:

SELECT 
w.player_id, 
p.group_id, 
w.score, 
RANK() OVER (PARTITION BY p.group_id ORDER BY score DESC) as group_placement
FROM
(
  SELECT player_id, SUM(score) score
  FROM (
    SELECT first_player as player_id, first_score as score
    FROM matches
    UNION ALL
    SELECT second_player, second_score
    FROM matches
  )
  GROUP BY player_id
) as w
inner join players p
on p.player_id = w.player_id

Nu udvælger vi bare de øverste i hver gruppe (rang =1) ved hjælp af WHERE

  SELECT 
  player_id, 
  group_id
  FROM
  (
      SELECT 
      w.player_id, 
      p.group_id, 
      w.score, 
      RANK() OVER (PARTITION BY p.group_id ORDER BY score DESC) as group_placement
      FROM
      (
        SELECT player_id, SUM(score) score
        FROM (
          SELECT first_player as player_id, first_score as score
          FROM matches
          UNION ALL
          SELECT second_player, second_score
          FROM matches
        )
        GROUP BY player_id
      ) as w
      inner join players p
      on p.player_id = w.player_id
    ) as gp
    WHERE group_placement = 1

Ser kompliceret ud? ja, men du kan se, at det endelige resultat bliver leveret lidt efter lidt. Hvert trin i dette er en 'undertabel', og du kan køre og observere dataene på hvert punkt.




  1. En enhedsspecifik sekvens

  2. Hvordan får man genererede nøgler af executeBatch uden ArrayIndexOutOfBoundsException?

  3. Java Date og MySQL tidsstempler tidszoner

  4. hvor sikre er BOB udarbejdede erklæringer