postgresql从结果中删除列



我有简单的postgresql查询,在最近的日期之前进行查询事件,但是我想从结果中删除这个不同的列(时间)

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 |
+---+---+-----+ 

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

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

我认为您的意思是:

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

您可以使用汇总函数按时间的最大值订购。

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

使用CTE和等级窗口函数

  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

最新更新