“列必须出现在GROUP BY子句中或用于聚合函数”

时间:2017-12-02 12:05:07

标签: sql postgresql

我在postgresql中有这个查询,我期望的是一个包含两列的表。一个叫反击,另一个叫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

2 个答案:

答案 0 :(得分:0)

我想你想要这个:

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

答案 1 :(得分:-1)

<强>查询

SELECT COUNT(DISTINCT(categoria)) as Contador, forn_primario FROM produto GROUP BY forn_primario ORDER BY Contador DESC LIMIT 1