这是我的示例数据
DateAndTime列每10秒测量一次
日期范围为6/30 ~ 8/31。
[DateAndTime],[TagName]为varchar(50(。
DateAndTime TagName DataValue
2022-06-30 14:15:40 BW004_GD-4-16 99
2022-06-30 14:15:50 BW004_GD-4-16 25
2022-06-30 14:16:00 BW004_GD-4-16 99
2022-06-30 14:16:10 BW004_GD-4-16 50
2022-06-30 14:16:20 BW004_GD-4-16 99
2022-06-30 14:16:30 BW004_GD-4-16 99
.
.
.
2022-06-30 14:15:40 BW004_GD-4-17 50
2022-06-30 14:15:50 BW004_GD-4-17 40
2022-06-30 14:16:00 BW004_GD-4-17 25
.
.
.
2022-06-30 18:20:00 BW004_GD-4-17 50
2022-06-30 18:20:10 BW004_GD-4-17 50
2022-06-30 18:20:20 BW004_GD-4-17 10
.
.
.
2022-06-30 14:15:40 BW004_GD-4-18 30
2022-06-30 14:15:50 BW004_GD-4-18 40
2022-06-30 14:16:00 BW004_GD-4-18 100
.
.
.
问题来了。
- DateAndtime是CharField,而不是日期字段
- 最大数据值重复
我想按DateAndTime排序,提取每个标记的最大和最早日期时间。
结果示例:
DateAndTime TagName MaxValue
2022-06-30 14:15:40 BW004_GD-4-16 99
2022-06-30 14:15:40 BW004_GD-4-17 50
2022-06-30 14:16:00 BW004_GD-4-18 100
.
.
.
SELECT LEFT([DateAndTime], 10) ,
[TagName]
, MAX([DataValue]) AS MaxValue
FROM [RTDB].[dbo].[Env_AI]
GROUP BY LEFT([DateAndTime], 10), [TagName]
ORDER BY [TagName]
此SQL有效,但不包括时间。
请帮帮我。谢谢。
使用dense_rank((按Date
和TagName
查找具有最大DataValue
(分区(的行
select *
from (
select *,
rn = dense_rank() over (
partition by left(DateAndTime, 10),
TagName
order by DataValue desc
)
from RTDB.dbo.Env_AI
) t
where rn = 1