[英]How to select several columns in Postgres without group by all columns
我正在使用Postgres 8.4.2,並且嘗試進行查詢以選擇一些數據,但是按我選擇的這幾列分組時,我得到了錯誤的結果。
我嘗試不對所有這些列進行分組,但是我注意到,我應該對所有選定的列進行分組。
我的查詢如下所示:
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;
我想選擇按offer_type = 1類別分類的商品。
如果不按幾列分組而僅按c.id
分組,我怎么辦呢?
我嘗試了以下窗口函數,但結果是相同的-它向我顯示了比應有的結果更多的結果。
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
我找到了我的問題的答案,它是:
SELECT distinct ON(ofr.id) ofr.id , c.id AS category_id, c.parent_id, c.title AS category_title,ofr.website_id ,
count( ofr.id)
OVER (PARTITION BY (select distinct on(ofr.id) ofr.id from offers as id GROUP 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.