我似乎无法围绕我需要开发的SQL查询。我需要计算传感器在规定时间内超过限制的时间百分比。
我表格中的数据如下所示:
Id, TimeStamp, Value, SensorName
1, 2018-03-16 00:00:01, 45, Temperature1
2, 2018-03-16 00:00:01, 53, Temperature2
3, 2018-03-16 00:00:02, 46, Temperature1
4, 2018-03-16 00:00:02, 54, Temperature2
4, 2018-03-16 00:00:03, 45, Temperature1
5, 2018-03-16 00:00:04, 46, Temperature1
6, 2018-03-16 00:00:05, 45, Temperature2
..........
每个传感器通常每秒都有一条记录,但如果传感器值没有变化,记录可能会减少。
我怎么能写一个查询,告诉我在过去一小时内Temperature1大于45的时间百分比?提前谢谢。
答案 0 :(得分:0)
将@temp替换为您的表名
select (cast(e.exceed as float)/cast(t.tot as float)) * 100.00 as [% exceed] from
(
select count(*) exceed
from @temp
where
SensorName = 'temperature1'
and TimeStamp between '2018-03-16 00:00:01' and '2018-03-16 00:00:02'
and Value > 45) e,
(
select count(*) tot
from @temp
where
SensorName = 'temperature1'
and TimeStamp between '2018-03-16 00:00:01' and '2018-03-16 00:00:02'
) t
答案 1 :(得分:0)
将SUM与条件值一起使用:
Declare @t table (Id int,[TimeStamp] datetime, [Value] int, SensorName nvarchar(30))
insert into @t values
(1,'2018-03-16 00:00:01',45,'Temperature1')
, (2,'2018-03-16 00:00:01',53,'Temperature2')
, (3,'2018-03-16 00:00:02',46,'Temperature1')
, (4,'2018-03-16 00:00:02',54,'Temperature2')
, (4,'2018-03-16 00:00:03',45,'Temperature1')
, (5,'2018-03-16 00:00:04',46,'Temperature1')
, (6,'2018-03-16 00:00:05',45,'Temperature2')
Declare @tempvalue int = 45
select sum(iif([Value]>@tempvalue,1.0,0.0))/count(*)*100
from @t
where SensorName = 'Temperature1'