sql - "column must appear in the GROUP BY clause or be used in an aggregate function"

标签 sql postgresql

我在 postgresql 中有这个查询,我期望的是一个包含两列的表。一个叫counter,另一个叫forn_primario。 但相反,我收到此错误:“列“forn_primario”必须出现在 GROUP BY 子句中或用于聚合函数中”

Select MAX(contador) as counter, forn_primario
From(
Select COUNT(DISTINCT categoria) as contador, forn_primario
From produto
Group by forn_primario)t

也在这个查询之后

Select COUNT(DISTINCT categoria) as contador, forn_primario
From produto
Group by forn_primario

我得到了这张表

 contador | forn_primario 
----------+---------------
        1 | 103246782
       17 | 113056729
        2 | 120456781
        3 | 123456719
        1 | 133956139
        2 | 143856248
        2 | 153756357
        1 | 163656466
        2 | 173516575
        1 | 183426684
        1 | 193336793

在主查询之后我应该有这张表:

  counter | forn_primario 
----------+---------------
       17 | 113056729

最佳答案

我想你想要这个:

Select COUNT(DISTINCT categoria) as contador, forn_primario
From produto
Group by forn_primario
Order by contador DESC
Limit 1;

关于sql - "column must appear in the GROUP BY clause or be used in an aggregate function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47607719/

相关文章:

SQL Server - 查询根据每年的最后值计算加权平均值

sql - 避免多对多表中的可空外键

sql - 多个 LEFT JOIN - "left"表是什么?

sql - 使用 generate_series 填充 PostgreSQL 中给定年份的月份列表

sql - 如何使用其他列类型在 postgres 中聚合 Jsonb 列

mysql - 如何以特定格式在MySQL数据库中保存日期?

mysql - 如何计算最近一年的 MySQL 中具有旧值的表?

sql - SQL Server 多行计算

sql - 使用多个连接、排序和小限制优化 PostgreSQL 查询

postgresql - docker postgres pgadmin 本地连​​接