返回最大值以及按月份分组的日期和时间值

返回最大值以及按月份分组的日期和时间值

问题描述:

使用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为您解答了这个问题,请将其标记为已回答。 –

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