我需要检索每个城市最近5天的预测信息。
我的表格如下所示
真正的问题在于发行日期。
该城市可能包含具有不同发行日期的同一日期的多个预测信息。
我需要检索每个城市的最近5条记录,其中包含最新发布日期和按预测日期分组
我尝试了类似下面的内容,但没有给出预期的结果
SELECT * FROM(
SELECT
ROW_NUMBER () OVER (PARTITION BY CITY_ID ORDER BY FORECAST_DATE DESC, ISSUE_DATE DESC) AS rn,
CITY_ID, FORECAST_DATE, ISSUE_DATE
FROM
FORECAST
GROUP BY FORECAST_DATE
) WHERE rn <= 5
任何建议或建议都会有所帮助
答案 0 :(得分:1)
这将获得每个城市最近5天内每天发布的最新预测:
SELECT *
FROM (
SELECT f.*,
DENSE_RANK() OVER ( PARTITION BY city_id ORDER BY forecast_date DESC )
AS forecast_rank,
ROW_NUMBER() OVER ( PARTITION BY city_id, forecast_date ORDER BY issue_date DESC )
AS issue_rn
FROM Forecast f
)
WHERE forecast_rank <= 5
AND issue_rn = 1;
答案 1 :(得分:0)
Partition by
的作用类似于group by
,但仅限于此功能。
尝试
with CTE as
(
select t1.*,
row_number() over (partition by city_id, forecast_date order by issue_date desc) as r_ord
from Forecast
)
select CTE.*
from CTE
where r_ord <= 5
答案 2 :(得分:0)
试试这个
SELECT * FROM(
SELECT
ROW_NUMBER () OVER (PARTITION BY CITY_ID, FORECAST_DATE order by ISSUE_DATE DESC) AS rn,
CITY_ID, FORECAST_DATE, ISSUE_DATE
FROM
FORECAST
) WHERE rn <= 5