Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL return multiple rows with DISTINCT though only latest date per second column

Lets says I have the following database table (date truncated for example only, two 'id_' preix columns join with other tables)...

+-----------+---------+------+--------------------+-------+

| id_table1 | id_tab2 | date | description        | price |

+-----------+---------+------+--------------------+-------+

| 1         | 11      | 2014 | man-eating-waffles | 1.46  |

+-----------+---------+------+--------------------+-------+

| 2         | 22      | 2014 | Flying Shoes       | 8.99  |

+-----------+---------+------+--------------------+-------+

| 3         | 44      | 2015 | Flying Shoes       | 12.99 |
+-----------+---------+------+--------------------+-------+

...and I have a query like the following...

SELECT id, date, description FROM inventory ORDER BY date ASC;

How do I SELECT all the descriptions, but only once each while simultaneously only the latest year for that description? So I need the database query to return the first and last row from the sample data above; the second it not returned because the last row has a later date.

like image 364
John Avatar asked Jan 01 '26 21:01

John


2 Answers

Postgres has something called distinct on. This is usually more efficient than using window functions. So, an alternative method would be:

SELECT distinct on (description) id, date, description
FROM inventory
ORDER BY description, date desc;
like image 172
Gordon Linoff Avatar answered Jan 03 '26 10:01

Gordon Linoff


The row_number window function should do the trick:

SELECT  id, date, description 
FROM    (SELECT id, date, description, 
                ROW_NUMBER() OVER (PARTITION BY description 
                                   ORDER BY date DESC) AS rn
         FROM   inventory) t
WHERE    rn = 1
ORDER BY date ASC;
like image 40
Mureinik Avatar answered Jan 03 '26 12:01

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!