我无法理解为什么下面的查询应该需要任何组?我不能让这个工作,而其他地方使用string_agg工作
任何建议赞赏
select dv.DocumentVersionID, dv.DocumentID, dv.AuthorUserID1, dv.AuthorUserID2, dv.AuthorUserID3,
(select string_agg(
((COALESCE ((', ' || author1.FirstName || ' ' || author1.LastName), ' ')) ||
(COALESCE ((', ' || author2.FirstName || ' ' || author2.LastName), ' ')) ||
(COALESCE ((', ' || author3.FirstName || ' ' || author3.LastName), ' '))) , ' ' )) as Authors
FROM DocumentVersion AS dv INNER JOIN
"User" AS author1 ON author1.UserID = dv.AuthorUserID1 LEFT OUTER JOIN
"User" AS author2 ON author2.UserID = dv.AuthorUserID2 LEFT OUTER JOIN
"User" AS author3 ON author3.UserID = dv.AuthorUserID3 ;
导致: -
ERROR: column "dv.documentversionid" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: select dv.DocumentVersionID, dv.DocumentID, dv.AuthorUserID1...
答案 0 :(得分:1)
因为select
没有from
子句所以引用都是外部查询。您有一个聚合函数,因此它们正在聚合。您也有非聚合列,因此需要group by
。
您既不需要子查询也不需要string_agg()
:
SELECT dv.DocumentVersionID, dv.DocumentID, dv.AuthorUserID1, dv.AuthorUserID2, dv.AuthorUserID3,
(COALESCE(', ' || author1.FirstName || ' ' || author1.LastName, ' ') ||
COALESCE(', ' || author2.FirstName || ' ' || author2.LastName, ' ') ||
COALESCE(', ' || author3.FirstName || ' ' || author3.LastName, ' ')
) as Authors
FROM DocumentVersion dv INNER JOIN
"User" author1
ON author1.UserID = dv.AuthorUserID1 LEFT OUTER JOIN
"User" author2
ON author2.UserID = dv.AuthorUserID2 LEFT OUTER JOIN
"User" author3
ON author3.UserID = dv.AuthorUserID3 ;
如果你想删除前导,
:
SELECT dv.DocumentVersionID, dv.DocumentID, dv.AuthorUserID1, dv.AuthorUserID2, dv.AuthorUserID3,
substr(COALESCE(', ' || author1.FirstName || ' ' || author1.LastName, ' ') ||
COALESCE(', ' || author2.FirstName || ' ' || author2.LastName, ' ') ||
COALESCE(', ' || author3.FirstName || ' ' || author3.LastName, ' '), 3
) as Authors
FROM DocumentVersion dv INNER JOIN
"User" author1
ON author1.UserID = dv.AuthorUserID1 LEFT OUTER JOIN
"User" author2
ON author2.UserID = dv.AuthorUserID2 LEFT OUTER JOIN
"User" author3
ON author3.UserID = dv.AuthorUserID3 ;
答案 1 :(得分:1)
所有未加入聚合函数的字段必须放在GROUP BY
子句中。
我只是无法理解您使用string_agg
的原因。简单的连接应该适用于您的情况。
SELECT
dv.documentversionid,
dv.documentid,
dv.authoruserid1,
dv.authoruserid2,
dv.authoruserid3,
COALESCE(author1.firstname||' '||author1.lastname,'')
||COALESCE(', '||author2.firstname|| ' '||author2.lastname,'')
||COALESCE(', '||author3.firstname||' '|| author3.lastname,'')
AS Authors
FROM
documentversion AS dv
INNER JOIN "user" AS author1 ON author1.userid = dv.authoruserid1
LEFT OUTER JOIN "user" AS author2 ON author2.userid = authoruserid2
LEFT OUTER JOIN "user" AS author3 ON author3.userid = authoruserid3