PARTITION BY ORDER BY组合使用

在with语句中使用PARTITION BY order by

WITH ranking AS (
  SELECT
    country,
    city,
    RANK() OVER(PARTITION BY country ORDER BY rating DESC) AS `rank`
  FROM store
)
SELECT
  country,
  city
FROM ranking
WHERE `rank` = 1;

PARTITION BY ORDER BY 和 window frames组合:

SELECT
  id,
  country,
  city,
  opening_day,
  rating,
  MAX(rating) OVER(
    PARTITION BY country
    ORDER BY opening_day
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM store;

分析函数 与 PARTITION BY ORDER BY组合:

lead():

SELECT
  country,
  city,
  opening_day,
  LEAD(city, 1, 'NaN') OVER(PARTITION BY country ORDER BY opening_day)
FROM store;

lag():

SELECT
  store_id,
  day,
  transactions,
  LAG(transactions) OVER(PARTITION BY store_id ORDER BY day) as `lag`,
  transactions - LAG(transactions) OVER(PARTITION BY store_id ORDER BY day) as `diff`
FROM sales
WHERE day BETWEEN '2016-08-05' AND '2016-08-10';

FIRST_VALUE():

SELECT
  country,
  city,
  rating,
  FIRST_VALUE(city) OVER(PARTITION BY country ORDER BY rating DESC)
FROM store;
上一篇:hdu3635 并查集


下一篇:2020 ICPC Asia East Continent Final D. City Brain(最短路+三分)