2017-07-06 41 views
1

使用MS-SQL 2012.嘗試從大型氣候數據集檢索特定數據字段時存在真正的難題。返回最大值以及按月份分組的日期和時間值

我已經剝離這個大的原始數據文件到一個臨時表稱爲#max_temp與它發生的時間和日期/供參考月份值沿着正確拉回每一天的最大值:

monthid month day time current_temp 
1  12  24 12:45 9.1 
1  12  25 12:25 8.3 
1  12  26 23:55 8.6 
1  12  27 00:00 8.6 
1  12  28 13:15 5.9 
1  12  29 12:50 5 
1  12  30 13:32 6.3 
1  12  31 12:49 6.9 
2  1  1 23:59 12 
2  1  2 01:12 12.7 
2  1  3 03:55 6.2 

我想要檢索是monthID分組輸出,所以返回:從尋找其他類似的問題

monthid  month day time current_temp 
    1  12  24 12:45 9.1 
    2  1  9 20:04 15.1 <<*not shown in above sample*>> 

我曾嘗試以下代碼,但沒有得到端到端解決方案或查詢失敗。

select * 
from (select t.*, ROW_NUMBER() over (partition by t.monthid, t.time order by t.current_temp desc) as rn 
from #max_temp t) x 
where rn=1 
order by monthid asc 

select monthid, day, time, current_temp 
from #max_temp 
where current_temp= (select max(current_temp) from #max_temp group by MonthID, day, time) 

提前感謝您的幫助, 埃利奧特。

+0

如果@SqlZim爲您解答了這個問題,請將其標記爲已回答。 –

回答

3

partition by像這樣刪除t.time

select * 
from (
    select t.*, ROW_NUMBER() over (partition by t.monthid order by t.current_temp desc) as rn 
    from #max_temp t 
) x 
where rn=1 
order by monthid asc 

在分區有time會給你最大的價值爲current_temp每個monthidtime,但因爲你只是想爲每個monthid最大current_temp,從該表達式中刪除time

+0

謝謝,就是這樣,我認爲它很接近....! –

+0

@ElliotWorth是的,非常接近!樂於幫助 – SqlZim

相關問題