PostgreSQL - GROUP BY子句或用于聚合函数汇合

时间:2017-01-25 12:23:26

标签: postgresql

我试图运行一些查询,这将带来每个用户创建的联系人输出,运行查询时出现以下错误,任何想法?

错误:

ERROR:  column "user_mapping.lower_username" must appear in the GROUP BY clause or be used in an aggregate function

查询:

SELECT 
    lower_username AS "Username", 
    display_name AS "Full Name", 
    count(DISTINCT CONTENT.title) AS "Pages created"
FROM 
    CONTENT
    LEFT JOIN 
    USER_MAPPING ON CONTENT.creator = USER_MAPPING.user_key
    LEFT JOIN 
    CWD_USER ON USER_MAPPING.lower_username = CWD_USER.lower_user_name
WHERE 
    creator IS NOT NULL AND 
    CONTENTTYPE IN ('PAGE', 'BLOGPOST')
GROUP BY creator
ORDER BY "Pages created" DESC;

1 个答案:

答案 0 :(得分:0)

例如,如果你有这样的情况:

lower_username   creator
-------------------------
A                X
B                X
C                Y
D                Y

如果您尝试按创建者分组,系统不知道如何处理lower_username。它将是

lower_username   creator
-------------------------
A                X
C                Y

OR

lower_username   creator
-------------------------
B                X
D                Y

因此您需要按其余列进行分组(在我的示例中为lower_username),或者在非分组列上应用某些聚合函数(例如,AVG,MAX等...)。您需要在一个分组值中只有一个值在其他列中(如果您通过select语句选择它们)。