2017-03-16 71 views
0

我需要檢索每個城市的最近5天預測信息。檢索最近發佈日期的每個城市的最近5天預測

我的表看起來像下面

enter image description here

真正的問題是發行日期。

該城市可能包含具有不同發佈日期的同一日期的多個預測信息。

我需要通過預測日期檢索最近的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 

enter image description here

任何建議或意見將有幫助

回答

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; 
+0

謝謝@ MT0像魅力一樣工作 – user3535945

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 
+0

工作不正常,請在您的解決方案中按照forecast_date,city_id進行分組,因此,r_ord <= 5將返回同一日期,同一城市的記錄 – user3535945

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 
+0

不按預期方式工作 – user3535945

+0

這將獲得前5天發佈的預測,沒有天數限制。不是OP想要的。 – MT0