I am having a db names products where i wanted to select the price of each product based on the id, but the price that i stored in the table is from different sources. So i want one latest price from each of the source. My table looks like this
id | name | source | updated_at | price
1 | ace | vanil | ... | 100
2 | vax | vanil | ... | 101
3 | tax | sunyil | ... | 200
1 | ace | sunyil | latest | 99.5
2 | vax | sunyil | latest | 100.5
3 | tax | vanil | latest | 199.5
3 | tax | vanil | ... | 220
3 | tax | vanil | ... | 211
3 | tax | vanil | ... | 205
3 | tax | sunyil | ... | 211
3 | tax | vanil | ... | 220
3 | tax | sunyil |latest_time | 220
1 | ace | sunyil | ... | 101
i want the output to be like this when my where condition is for id=3
id | name | source | updated_at | price
3 | tax | vanil | latest time| 199.5
3 | tax | sunyil | latest time| 220
i tried running the
select * from products WHERE id= '3' ORDER BY updated_at DESC LIMIT 1
but this one brings only one row irrespective of the source
could any one help me out with this. I am extremely new to postgres and sql queries. I would really appreciate your help.
CodePudding user response:
It's not really clear what you want to do. If you would like to sum the price for the product with id 3 not having the text "..." in the column "updated_at", you can do this query:
SELECT id, name, source, updated_at, SUM(price) FROM products
WHERE id = 3 and updated_at != '...'
GROUP BY id, name, source, updated_at ORDER BY updated_at;
See this example and try out: db<>fiddle Modify the query to your desires if necessary.
CodePudding user response:
Using DISTINCT ON
:
SELECT DISTINCT ON (id, source) *
FROM products
WHERE id = 3
ORDER BY id, source, updated_at DESC;