Postresql, max returns all rows with same ids

All we need is an easy explanation of the problem, so here it is.

System

PostgreSQL 11.5 (Ubuntu 11.5-1.pgdg19.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 8.3.0-6ubuntu1) 8.3.0, 64-bit

Issue

Need return one max value from table for every product_id (1 product_id has 10 store_ids) based on available_count.

Sql

select
    product_id, store_id, max(available_count)
from
    j_product_store_availability
group by
    product_id,
    store_id,
    available_count
order by
    product_id,
    available_count desc,
    store_id
--limit 1

Result

product_id store_id available_count

130475  4   7
130475  1   4
130475  8   4
130475  2   3
130475  5   3
130475  7   3
130475  10  3
130475  3   2
130475  6   2
130475  9   0
130479  1   0
130479  2   0
130479  3   0
...

It returns rows for every store_id. Need to return just one max value based on available_count.

Expected result

130475  4   7
130479  1   0
(next product_id)
...

Thanks.

Solution (Laurenz solution)

SELECT DISTINCT ON (product_id)
product_id,
store_id,
max(available_count)
from
j_product_store_availability
--where store_id = '7'
group by
product_id,
store_id,
available_count
ORDER by
product_id,
available_count desc;

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

If using a non-standard PostgreSQL construct is no problem, the easiest way would be

SELECT DISTINCT ON (product_id)
       product_id, store_id, available_count
FROM j_product_store_availability
ORDER BY product_id, available_count DESC, store_id;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply