Sql DISTINCT 从结果中删除列

Sql DISTINCT remove column from result

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

中删除这个 Distinct column(time)
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 |
+---+---+-----+ 

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

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

我想你的意思是这样的:

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

使用CTE and rank 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

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

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