如何使用 SQL 为每天的每个位置 select 一行?

How to select a row for every location for every day using SQL?

我有一个数据库,其中存储了两个位置的一些预报。每个位置都有 3 天的预报,每天每小时都有多个预报。 我想select每天每个位置的 3 个最新预报的平均温度。位置保存为“位置”,每天保存为“applicable_date”,每天每小时都有一个预报保存为“创建”。我正在尝试类似的方法但不起作用:

SELECT * FROM (
    SELECT * FROM `forecast` GROUP BY location
) GROUP BY applicable_date 
ORDER BY created DESC 
LIMIT 3
SELECT location, 
       CAST(created AS DATE) `date`, 
-- or  applicable_date `date`,
       MAX(created) last_datetime
FROM forecast
GROUP BY 1, 2;

像这样应该没问题。这些 return 每个 day/location 的整个预测行。

对于 8.0+ 版本:

WITH cte AS (
       SELECT *
            , ROW_NUMBER() OVER (PARTITION BY location, applicable_date ORDER BY created DESC ) AS rn
         FROM forecast
     )
SELECT *
  FROM cte
 WHERE rn = 1
;

对于 8.0+ 及之前的版本:

SELECT f.*
  FROM (
       SELECT location, applicable_date
            , MAX(created) AS max_created
         FROM forecast
        GROUP BY location, applicable_date
     ) AS cte
  JOIN forecast AS f
    ON f.location        = cte.location
   AND f.applicable_date = cte.applicable_date
   AND f.created         = cte.max_created
;