sqlzoo 9-.Window functions answers

If you have any questions, please comment or chat in private. Please chat with the blogger privately, thank you.

Link to the original title: https://sqlzoo.net/wiki/Window_functions

Other question solution links: https://blog.csdn.net/aiqiyizz/article/details/109057732

The solution corresponds to the English version.

This section should be about some commonly used functions

9- Window function

9-.1 Warming up

SELECT lastName, party, votes
  FROM ge
 WHERE constituency = 'S14000024' AND yr = 2017
ORDER BY votes DESC

9-.2 Who won?

SELECT party, votes,
       RANK() OVER (ORDER BY votes DESC) as posn
  FROM ge
 WHERE constituency = 'S14000024' AND yr = 2017
ORDER BY party

9-.3

SELECT yr,party, votes,
      RANK() OVER (PARTITION BY yr ORDER BY votes DESC) as posn
  FROM ge
 WHERE constituency = 'S14000021'
ORDER BY party,yr

9-.4

Output format:constituency, party, votes, rank

It’s not difficult to know what to output

SELECT constituency,party, votes, RANK() OVER (PARTITION BY constituency ORDER BY votes DESC) AS rank
  FROM ge
 WHERE constituency BETWEEN 'S14000021' AND 'S14000026'
   AND yr  = 2017
 ORDER BY rank, constituency

9-.5 Winners Only

The previous question and the application of SELECT IN SELECT

SELECT constituency, party
FROM (
  SELECT constituency,party, votes, RANK() OVER (PARTITION BY constituency ORDER BY votes DESC) AS rank
    FROM ge
  WHERE constituency BETWEEN 'S14000021' AND 'S14000026'
    AND yr  = 2017
  ORDER BY rank, constituency
) temp1
WHERE rank = 1

9-.6 Scottish seats

The question seems a bit slang? Difficult to understand the meaning of the question. I only understand the data after reading the data.

how many seats for each party in Scotland ⇒ \Rightarrow Winner of the previous title meaning

Occupying a seat corresponds to the winner, forgive my poor understanding.

SELECT party, COUNT(*) AS winner
FROM (
  SELECT constituency,party, votes, RANK() OVER (PARTITION BY constituency ORDER BY votes DESC) AS rank
    FROM ge
  WHERE constituency LIKE 'S%'
    AND yr  = 2017
  ORDER BY rank, constituency
) temp1
WHERE rank = 1
GROUP BY party

Guess you like

Origin blog.csdn.net/aiqiyizz/article/details/109096955