【问题标题】:Return Maximum Value along with day + time value grouped by month返回最大值以及按月分组的日期+时间值
【发布时间】:2017-07-06 16:06:40
【问题描述】:

使用 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)

提前感谢您的帮助, 艾略特。

【问题讨论】:

  • 如果@SqlZim 为您回答了这个问题,请将其标记为已回答。

标签: sql-server datetime group-by max


【解决方案1】:

像这样从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 将为您提供每个monthidtime 的最大current_temp 值,但由于您只希望每个monthid 的最大current_temp 值,请删除time从那个表情。

【讨论】:

  • @ElliotWorth 是的,非常接近!乐于助人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
相关资源
最近更新 更多