I have an SQL Server database, that logs weather device sensor data.
The table looks like this:
Id DeviceId SensorId Value 1 1 1 42 2 1 1 3 3 1 2 30 4 2 2 0 5 2 1 1 6 3 1 26 7 3 1 23 8 3 2 1
In return the query should return the following:
Id DeviceId SensorId Value 2 1 1 3 3 1 2 30 4 2 2 0 5 2 1 1 7 3 1 23 8 3 2 1
For each device the sensor should be unique. ie Values in Columns DeviceId and SensorId should be unique (row-wise).
Apologies if I'm not clear enough.
If you don't want to sum Value
as your desired result suggest, so you just want to take an "arbitrary" row of each "DeviceId + SensorId"-group:
WITH CTE AS
(
SELECT Id, DeviceId, SensorId, Value,
RN = ROW_NUMBER() OVER (PARTITION BY DeviceId, SensorId ORDER BY ID DESC)
FROM dbo.TableName
)
SELECT Id, DeviceId, SensorId, Value
FROM CTE
WHERE RN = 1
ORDER BY ID
This returns the row with the highest ID per group. You need to change ORDER BY ID DESC
if you want a different result. Demo: http://sqlfiddle.com/#!6/8e31b/2/0 (your result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.