如何在Postgres中选择多个列而不是所有列的组

时间:2016-01-27 19:22:07

标签: sql postgresql select group-by postgresql-8.4

我正在使用Postgres 8.4.2并且我正在尝试创建一个选择某些数据的查询,但是当我选择这几列时,我得到错误的结果。

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

我的查询如下:

setFillAfter(true)

我想按类别选择要约数,其中offer_type = 1。

我怎么能在没有分组的情况下通过多个列进行分组,但只能按 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; 分组?

我尝试了以下窗口函数但结果是一样的 - 它显示了比它应该更多的结果。

c.id

1 个答案:

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