可以将聚合函数与join一起使用吗?

时间:2020-04-29 06:11:57

标签: sql postgresql join grouping aggregate-functions

  • 表项目:pid(pk),名称...
  • 表类别:pid(pk),project(项目的pid),parent(其他类别的pid)...
  • 表计数:项目(项目的pid),类别(类别的pid),计数...

我之前使用过此查询

SELECT
categories.*, projects.pid, projects.name, parent_category.*
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent

效果很好

这次,我们需要SUM,COUNT个数据。所以我添加了“ counts”表并进行了查询。

SELECT
categories.*, projects.pid, projects.name, SUM(counts.count), COUNT(counts.count),
parent_category.*, SUM(parent_category_count.count), COUNT(parent_category_count.count)
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN counts ON counts.category = categories.pid
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid

然后我得到

错误:聚合函数调用无法嵌套

我该怎么办?这个查询基本上有意义吗?还是应该拆分?

1 个答案:

答案 0 :(得分:1)

您应该添加适当的GROUP BY子句(在您的情况下应为Categories.pid)

    SELECT
    categories.*
    , projects.pid
    , projects.name
    , SUM(counts.count)
    , COUNT(counts.count)
    , parent_category.*
    , SUM(parent_category_count.count)
    , COUNT(parent_category_count.count)
    FROM categories
    INNER JOIN projects ON projects.pid = categories.project
    LEFT JOIN counts ON counts.category = categories.pid
    LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
    LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
    GROUP BY categories.pid 

或根据您的评论

    SELECT
    categories.*
    , projects.pid
    , projects.name
    , SUM(counts.count)
    , COUNT(counts.count)
    , parent_category.*
    , SUM(parent_category_count.count)
    , COUNT(parent_category_count.count)
    FROM categories
    INNER JOIN projects ON projects.pid = categories.project
    LEFT JOIN counts ON counts.category = categories.pid
    LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
    LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
    GROUP BY categories.pid, projects.pid, parent_category.pid