sql - 从表中查找最大值和最小值及其相应的插入时间
问题描述
我有一张表,每天插入多条记录。现在我想在单个查询中选择给定月份的每一天的最大值和最小值以及它们各自插入的 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。
解决方案
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。
推荐阅读
- node.js - 在 NodeJS 中解析 SQL 响应
- python - 从表单生成的 FLASK 表
- git - Git - 快进 1 或 N 次提交
- sql-server - transact-SQl 查询左连接两个表并从表中获取所有数据
- android - Expo 将 App 更新到 Play 商店 - 密钥错误
- jenkins - 在创建 URL 时转义空行
- python - 创建字符串 Python 的所有可能变体
- python - 如何从discord.py中的特定角色值中随机抽取
- java - 在 CPLEX for Java 中设置时间限制
- snowpack - snowpack:项目文件夹之外的参考文件