首页 > 解决方案 > 从表中查找最大值和最小值及其相应的插入时间

问题描述

我有一张表,每天插入多条记录。现在我想在单个查询中选择给定月份的每一天的最大值和最小值以及它们各自插入的 DateTime。

表架构

DtTime   datetime
Value1   decimal(18,2)  

样本数据

DtTime                    Value1    
--------------------------------    
2020-01-09 22:29:17.000    0.00
2020-01-09 22:30:41.000    0.40
2020-01-09 22:33:58.000    0.10
2020-01-09 22:34:59.000    2.49
2020-01-09 22:35:40.000    0.00
2020-01-10 00:33:07.000    0.10
2020-01-10 00:34:34.000    2.69
2020-01-10 00:37:06.000    2.67
2020-01-10 00:40:19.000    2.52
2020-01-15 08:34:34.000    0.69
2020-01-15 11:37:06.000    6.67
2020-01-15 04:40:19.000    2.52

期望的输出

Min     MinTime                   Max        MaxTime
-------------------------------------------------------------------    
0.00    2020-01-09 22:29:17.000   2.49      2020-01-09 22:34:59.000
0.10    2020-01-10 00:33:07.000   2.69      2020-01-10 00:34:34.000
0.69    2020-01-15 08:34:34.000   6.67      2020-01-15 11:37:06.000

同样,对于给定月份的所有日子,如果记录在某一天不存在,那么它将在所有字段中显示 0。

标签: sqlsql-server

解决方案


SQL Server 没有“第一个”和“最后一个”聚合函数。但是您可以为此目的使用窗口函数:

select distinct cast(dttime as date) as dte,
       min(Value1) over (partition by cast( dttime as Date) ) as maxValue,
       first_value(dttime) over (partition by cast( dttime as Date) order by value1 asc) as min_time,
       max(Value1) over (partition by cast( dttime as Date) ) as maxValue,
       first_value(dttime) over (partition by cast( dttime as Date) order by value1 desc) as max_time
from t
order by dte;

是一个 db<>fiddle。


推荐阅读