我有这个DB表,其中不断添加数据。正在添加的数据是传感器数据,因此每小时每个传感器有两个读数。我想知道一种方法,只获得整个月的最后一天阅读。例如,
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天数等等。不太喜欢我的应用程序。有人可以帮忙吗?谢谢。
答案 0 :(得分: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
答案 1 :(得分:1)
您可以使用聚合,即MAX()
来处理此问题。这是MSDN:
http://msdn.microsoft.com/en-us/library/ms187751.aspx
返回表达式中的最大值。可能紧随其后 OVER条款。
您的查询将导致:
SELECT SensorID, MAX(Date_reading) FROM NewLogTable GROUP BY Sensor_ID
答案 2 :(得分:1)
您可以使用row_number()
窗口函数来实现此目的
select * from
(
select
*,
row_number() over (partition by date_reading order by datetimestamp desc) rn
from yourtable
) v
where rn = 1
答案 3 :(得分: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
的结束值有时间部分。
答案 4 :(得分:0)
SELECT TOP 1 *
FROM dbo.NewLogTable
WHERE Sensor_ID = '12345'
AND Date_Reading <= '2012-08-01'
ORDER BY DateTimeSTap DESC