Sql DISTINCT从结果中删除列

时间:2016-06-14 12:04:56

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

我有简单的PostgreSQL查询,它按最近的日期查询事件,但是 我想从结果

中删除此Distinct列(时间)
SELECT DISTINCT time, sensor_id, event_type, value from events ORDER BY sensor_id

+---------------------+---+---+-----+
| 2014-02-13 12:42:00 | 2 | 2 |   5 |
| 2014-02-13 13:19:57 | 2 | 4 | -42 |
| 2014-02-13 13:32:36 | 2 | 3 |  54 |
| 2014-02-13 14:48:30 | 2 | 2 |   2 |
| 2014-02-13 12:54:39 | 3 | 2 |   7 |
+---------------------+---+---+-----+

需要这样的结果

+---+---+-----+
| 2 | 2 |   5 |
| 2 | 4 | -42 |
| 2 | 2 |   2 |
| 2 | 3 |  54 |
| 3 | 2 |   7 |
+---+---+-----+ 

4 个答案:

答案 0 :(得分:2)

您可以使用PostgreSQL DISTINCT ON (...)功能:

SELECT DISTINCT ON (time, sensor_id, event_type, value)
       sensor_id, event_type, value from events
ORDER BY sensor_id;

答案 1 :(得分:1)

我认为你的意思是:

SELECT sensor_id, event_type, value 
from   (
          SELECT DISTINCT time, sensor_id, event_type, value from events
       ) A 
ORDER BY sensor_id

答案 2 :(得分:0)

您可以使用聚合函数按最大时间值排序。

SELECT  sensor_id, event_type, value
FROM events 
GROUP BY sensor_id, event_type, value
ORDER BY MAX(time) DESC

答案 3 :(得分:0)

USE CTE和排名window功能

  with temp as
    ( select time,sensor_id, event_type, value , rank() OVER (PARTITION BY     ensor_id, event_type, value order by 'time') as rnk
       )
       select time,sensor_id, event_type, value from temp  where rnk =1