I'm using Postgres 8.4.2 and I'm trying to make a query that selects some data but I get wrong results when group by these several columns I select.
I tried not to group by all of these columns, but I get notice, that I should group by all selected columns.
My query looks like that:
SELECT c.id AS category_id, c.parent_id, c.title AS category_title, count(ofrs.id) AS offers_count
FROM categories c
LEFT JOIN offers_to_categories otc ON c.id = otc.category_id
LEFT JOIN offers ofrs ON otc.offer_id = ofrs.id
WHERE ofrs.offer_type = 1 AND ofrs.status = 1
GROUP BY c.id, c.title, c.parent_id;
I want to select offers count by category where offer_type = 1.
How could I do that without group by several columns but only group by c.id?
I tried the following window function but result is the same - it shows me more results than it should be.
SELECT ofr.id , c.id AS category_id, c.parent_id, c.title AS category_title,ofr.website_id ,
count( ofr.id)
OVER (PARTITION BY (ofr.id) order BY ofr.id)
FROM offers AS ofr
INNER JOIN offers_to_categories AS ofr_cat ON (ofr_cat.offer_id = ofr.id)
INNER JOIN categories AS c ON (c.id = ofr_cat.category_id)
WHERE (c.id = 3 or c.parent_id = 3) and ofr.website_id = 1 and ofr.status = 1
min()ormax()to pull out the values you need.