0

我有这个数据库表,其中不断添加数据。添加的数据是传感器数据,因此每个传感器每小时有两个读数。我想知道一种方法来获取整个月当天的最后一次读数。例如,

select * from dbo.NewLogTable
where Sensor_ID= '12345'and Date_Reading between '2012-08-01' and '2012-08-31' 
and DateTimeStamp between '23:30:00'and '23:59:00'
order by DateTimeStamp asc

我知道这不起作用,但它是我想要的伪代码。同样,这里的目标是每天只获得一个特定传感器的读数(最新)。我已经看到很多例子,其中显示了一个月的第一天和最后一天,显示过去 x 天等。不太像我的应用程序。任何人都可以帮忙吗?谢谢。

4

5 回答 5

2
WITH
  sequenced AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY sensor_id, Date_Reading ORDER BY DateTimeStamp DESC) AS daily_sequence_id,
    *
  FROM
    dbo.NewLogTable
)
SELECT
  *
FROM
  sequenced
WHERE
  sensor_id = '12345'
  AND Date_Reading BETWEEN '2012-08-01' AND '2012-08-31'
  AND daily_sequence_id = 1
于 2012-10-22T14:27:07.177 回答
1

您可以使用聚合,即MAX()处理此问题。这是 MSDN:

http://msdn.microsoft.com/en-us/library/ms187751.aspx

返回表达式中的最大值。后面可以跟 OVER 子句。

您的查询将导致:

SELECT SensorID, MAX(Date_reading) FROM NewLogTable GROUP BY Sensor_ID
于 2012-10-22T14:25:24.573 回答
1

您可以使用row_number()窗口功能来实现这一点

select * from
(
    select 
        *, 
        row_number() over (partition by date_reading order by datetimestamp desc) rn 
    from yourtable
) v
where rn = 1
于 2012-10-22T14:26:33.190 回答
1

您可以DATEPART结合使用该函数MAX来获取整个月的日期读数:

SELECT DATEPART(d, Date_Reading) AS day, MAX(value) AS value FROM table
WHERE Sensor_ID = '12345' 
    AND Date_Reading BETWEEN '2012-08-01' AND '2012-08-31 23:59:59'
GROUP BY DATEPART(d, Date_Reading)

只要确保你的最终价值BETWEEN有一个时间部分。

于 2012-10-22T14:27:59.250 回答
0
SELECT TOP  1 * 
FROM dbo.NewLogTable
WHERE Sensor_ID = '12345'
AND Date_Reading <= '2012-08-01'
ORDER BY DateTimeSTap DESC 
于 2012-10-22T14:29:15.637 回答