2016-01-27 19 views
0

我正在使用Postgres 8.4.2,我试图做一个查询来选择一些数据,但是当我选择这几列时,我得到了错误的结果。如何在Postgres中选择几列而不是所有列的组

我试图不按所有这些列进行分组,但我注意到,我应该按所有选定列进行分组。

我的查询看起来像这样:

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 
+3

退房窗口功能。而且你应该真正计划对受支持版本进行更新。 8.4是非常古老的。你至少应该升级到最新的8.4版本 –

+0

我现在正在阅读关于他们 - http://www.postgresql.org/docs/8.4/static/tutorial-window.html。但我不明白如何使用它只由ofr.id分组。我编辑了我的问题。 –

+0

请编辑您的问题并添加一些示例数据和预期的输出 –

回答

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 
相关问题