简体   繁体   中英

In postgresql how to use group by and fetch all the columns

I am new in writing raw sql queries and not able to find the solution for my problem, this is the sample the data in my postgresql table-

              product_id              | stage |           added_on            | stage_id | plan_id | producer_id 
--------------------------------------+-------+-------------------------------+----------+---------+-------------
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    70 | 2017-03-11 13:36:52.21992+00  |     1463 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    60 | 2017-03-11 13:36:36.293494+00 |     1462 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    50 | 2017-03-11 13:36:31.923588+00 |     1461 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    40 | 2017-03-11 13:35:02.299077+00 |     1460 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    30 | 2017-03-11 13:34:53.541734+00 |     1459 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    20 | 2017-03-11 13:34:46.650811+00 |     1458 |      60 |         137
 a0361a6f-5cd0-4b3e-98ad-6be115983496 |    10 | 2017-03-11 13:34:20.866694+00 |     1457 |      60 |         137
 619c5d60-1815-47d5-9602-7faf355f953b |   -30 | 2017-03-11 13:34:10.968819+00 |     1456 |      60 |         137
 619c5d60-1815-47d5-9602-7faf355f953b |    10 | 2017-03-11 13:34:10.39307+00  |     1455 |      60 |         137

I want to fetch the result in such a way which can return me the first row and last row. Means I want to lookup on most recent row group by product_id. I tried the below query-

select product_id, max(added_on) from product_stages where producer_id = 137 group by product_id;

This gives me satisfying result but I want to select other columns as well so when I try below it gives me error.

 select product_id, stage, stage_id, plan_id, max(added_on) from product_stages where producer_id = 137 group by product_id;

What is the good way to achieve this? Thanks in Advance.

Use DISTINCT ON instead of GROUP BY :

select distinct on (product_id) *
from product_stages 
where producer_id = 137 
order by product_id, added_on desc;

SELECT DISTINCT ON expressions must match initial ORDER BY expressions so product_id has to be the first column in ORDER BY . However you can use a derived table to freely sort the results by other columns, eg:

select *
from (
    select distinct on (product_id) *
    from product_stages 
    where producer_id = 137 
    order by product_id, added_on desc
    ) s
order by added_on desc;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM