简体   繁体   English

选择查询以获取两列中的唯一单元格

[英]Select Query to Get Unique Cells in Two Columns

I have an SQL Server database, that logs weather device sensor data. 我有一个SQL Server数据库,用于记录天气设备传感器数据。

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). 即,DeviceId和SensorId列中的值应该是唯一的(逐行)。

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: 如果您不希望对Value进行求和,则只希望对每个“ DeviceId + SensorId”-组使用“任意”行:

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. 这将返回每个组具有最高ID的行。 You need to change ORDER BY ID DESC if you want a different result. 如果需要不同的结果,则需要更改ORDER BY ID DESC Demo: http://sqlfiddle.com/#!6/8e31b/2/0 (your result) 演示: http : //sqlfiddle.com/#!6/8e31b/2/0 (您的结果)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM