从表

时间:2017-12-12 21:28:47

标签: sql postgresql greatest-n-per-group

我使用postgres作为后端来存储sensordata。各种传感器以不同的频率记录。我想获得每个不同值的最后一个。即我有下表:

   id   | sensorid | type |   value    |           datetime            
--------+----------+------+------------+-------------------------------
 302888 |        9 |  118 |       4829 | 2017-12-12 22:20:04.911429+01
 302887 |        9 |  116 |      17000 | 2017-12-12 22:20:04.90125+01
 302886 |        9 |  104 |      40400 | 2017-12-12 22:20:04.827895+01
 302885 |        5 |  116 | 4294958596 | 2017-12-12 22:19:04.813092+01
 302884 |        5 |  104 |      76100 | 2017-12-12 22:19:04.803245+01
 302883 |        5 |  118 |       3976 | 2017-12-12 22:19:04.753291+01
 302882 |        5 |  116 | 4294958596 | 2017-12-12 22:16:18.730765+01
 302881 |        5 |  104 |      76100 | 2017-12-12 22:16:18.720933+01
 302880 |        5 |  118 |       3976 | 2017-12-12 22:16:18.700545+01
 302879 |        1 |  118 |       5410 | 2017-12-12 22:15:54.688361+01
 302878 |        1 |  116 |      19000 | 2017-12-12 22:15:54.67866+01
 302877 |        1 |  104 |      33700 | 2017-12-12 22:15:54.660863+01
 302876 |        9 |  118 |       4892 | 2017-12-12 22:15:04.646695+01

等等。

我想了解以下数据:

   id   | sensorid | type |   value    |           datetime            
--------+----------+------+------------+-------------------------------
 302888 |        9 |  118 |       4829 | 2017-12-12 22:20:04.911429+01
 302887 |        9 |  116 |      17000 | 2017-12-12 22:20:04.90125+01
 302886 |        9 |  104 |      40400 | 2017-12-12 22:20:04.827895+01
 302885 |        5 |  116 | 4294958596 | 2017-12-12 22:19:04.813092+01
 302884 |        5 |  104 |      76100 | 2017-12-12 22:19:04.803245+01
 302883 |        5 |  118 |       3976 | 2017-12-12 22:19:04.753291+01
 302879 |        1 |  118 |       5410 | 2017-12-12 22:15:54.688361+01
 302878 |        1 |  116 |      19000 | 2017-12-12 22:15:54.67866+01
 302877 |        1 |  104 |      33700 | 2017-12-12 22:15:54.660863+01

所以我希望每个sensorid和类型组合的id或日期时间最长的行。这可以用一个sql语句吗?

2 个答案:

答案 0 :(得分:2)

我为此目的喜欢distinct on

select distinct on (sensorid, value) sd.*
from sensordata sd
order by sensorid, value, datetime desc;

答案 1 :(得分:1)

这应该做的工作:

SELECT
A.ID, A.SENSORID, A.TYPE, A.VALUE, A.DATETIME
FROM
(
    SELECT
    ID, SENSORID, TYPE, VALUE, DATETIME, ROW_NUMBER() OVER (PARTITION BY SENSORID, TYPE ORDER BY ID DESC) AS RNUM
    FROM
    YOUR_TABLE
) A
WHERE A.RNUM = 1;  

编辑仅供参考我使用ID订购。根据您的问题,似乎最高ID表示最新的。所以它应该有意义。如果日志记录以时间顺序发生并且您希望获得最新记录,也可以由DATETIME完成。