0

我将传感器读数存储在表格中,数据是仪表读数:

CaptureDate               SensorID      Value
2020-01-11 14:15:33.350   121           23908,0000
2020-01-11 14:00:33.300   123           23161,0000
2020-01-11 14:00:33.240   121           23901,0000
2020-01-11 13:45:33.137   123           23154,0000
2020-01-11 13:45:33.073   121           23894,0000
2020-01-11 13:30:32.927   123           23147,0000

我需要使用 SQL 来获取按 SensorID 过滤的一个月的每日总计,以获得类似于以下内容:

Date        SensorID    Value
2020-01-10  121         319
2020-01-11  121         249
2020-01-12  121         289
2020-01-13  121         263
2020-01-14  121         314
2020-01-15  121         248

我试图获得按天分组的最小值和最大值,但我无法获得计数器的差异来获得净值;

SELECT * 
FROM Records
WHERE CaptureDate in 
(
    SELECT min(CaptureDate)
    FROM Records
    WHERE SensorID = 124
        AND convert(date, CaptureDate) >= '2020-01-01'
    GROUP BY convert(date, CaptureDate)
) OR CaptureDate IN (
    SELECT Max(CaptureDate)
    FROM Records
    WHERE SensorID = 124
        AND convert(date, CaptureDate) >= '2020-01-01'
    GROUP BY convert(date, CaptureDate)
) ORDER BY CaptureDate

并返回:

CaptureDate               SensorID  Value   
2020-01-08 14:20:39.627   121       23601.0000
2020-01-08 17:50:39.843   121       23678.0000
2020-01-09 08:50:19.473   121       23678.0000
2020-01-09 18:05:20.300   121       23707.0000
2020-01-10 08:46:06.903   121       23707.0000
2020-01-10 18:15:20.007   121       23796.0000
4

5 回答 5

0

这应该有效:

演示:DB 小提琴

select 
  convert(date, capturedate) date_only, 
  sensorid, 
  min(value) min_val, 
  max(value) max_val,
  max(value) - min(value) diff
from records
group by convert(date, capturedate), sensorid
于 2020-01-14T08:57:51.447 回答
0

试试看

With DailyMinMax AS
(
  SELECT 
    CAST(CaptureDate AS date) date,
    SensorID,
    MIN(Value) minvalue,
    Max(Value) maxvalue
  FROM Records 
  GROUP BY CAST(CaptureDate AS date), SensorID
)
SELECT 
  date,
  SensorID,
  maxvalue-minvalue AS MaxMinDifference 
FROM DailyMinMax 
于 2020-01-14T08:45:36.923 回答
0

我没有测试过,但解决方案应该与此类似。您创建了两个不同的表,一个具有每日最小值,另一个具有 dailt 最大值,然后加入它们:

SELECT mx.CaptureDate, mx.value - mn.value FROM
(
    SELECT CaptureDate, min(CaptureDate) value
    FROM Records
    WHERE SensorID = 124
        AND convert(date, CaptureDate) >= '2020-01-01'
    GROUP BY convert(date, CaptureDate)
) mn, (
    SELECT CaptureDate, Max(CaptureDate) value
    FROM Records
    WHERE SensorID = 124
        AND convert(date, CaptureDate) >= '2020-01-01'
    GROUP BY convert(date, CaptureDate)
) mx 
WHERE mx.CaptureDate = mn.CaptureDate
ORDER BY mx.CaptureDate  
于 2020-01-14T08:45:39.443 回答
0

我找到了解决方案!没有什么比暴露问题来澄清我的想法更好的了

SELECT SensorID, CAST(CaptureDate AS DATE) AS Date, MAX(Value)-MIN(Value) As dValue
FROM Readings
WHERE SensorID = 121
GROUP BY CAST(CaptureDate AS DATE), SensorID
ORDER BY CaptureDate

现在多么容易!:D

于 2020-01-14T08:55:50.647 回答
-1

我建议尝试将聚合计数存储在单独的列中,并在该列上运行您的查询。我不认为按聚合分组会持续存在并传递给外部查询。

于 2020-01-14T08:51:32.973 回答