PostgreSQL aggregate or window function to return just the last value

放肆的年华 提交于 2019-12-04 06:20:51
Erwin Brandstetter

DISTINCT plus window function

Add a DISTINCT clause:

SELECT DISTINCT a
     , last_value(b) OVER (PARTITION BY a ORDER BY b
                           RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM  (
   VALUES
     (1, 'do not want this')
    ,(1, 'just want this')
   ) sub(a, b);

More about DISTINCT:

Simpler and faster with DISTINCT ON

PostgreSQL also has this extension of the SQL standard:

SELECT DISTINCT ON (a)
       a, b
FROM  (
   VALUES
     (1, 'do not want this')
   , (1, 'just want this')
   ) sub(a, b)
ORDER  BY a, b DESC;

More about DISTINCT ON and possibly faster alternatives:

Simple case with plain aggregate

If your case is actually as simple as your demo (and you don't need additional columns from that last row), a plain aggregate function will be simpler:

SELECT a, max(b)
FROM  (
   VALUES
     (1, 'do not want this')
   , (1, 'just want this')
   ) sub(a, b)
GROUP  BY a;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!