子查询Count() - 列必须出现在GROUP BY子句中

时间:2017-04-06 21:33:01

标签: sql postgresql

我只是想知道,为什么子查询返回了多个值,所以我提出了这个问题:

SELECT id, 
    (SELECT Count(tags[i]) 
        FROM generate_subscripts(tags, 1) AS i 
        WHERE tags[i]='oneway') as oneway_string 

    FROM planet_osm_ways 
    WHERE 'oneway' = ANY(tags) 
    HAVING 
        (SELECT Count(tags[i]) 
            FROM generate_subscripts(tags, 1) AS i 
            WHERE tags[i]='oneway')  > 1

哪一个应该找到所有出现的'单向'在tags数组中并计算它们。

[42803] ERROR: column "planet_osm_ways.id" must appear in the GROUP BY clause 
               or be used in an aggregate function Position: 8

1 个答案:

答案 0 :(得分:0)

您应该将HAVING更改为WHERE,因为您没有可以应用HAVING过滤器的群组,而是希望使用适用于每一行的WHERE过滤器

SELECT id, 
(SELECT Count(tags[i]) 
    FROM generate_subscripts(tags, 1) AS i 
    WHERE tags[i]='oneway') as oneway_string 

FROM planet_osm_ways 
WHERE 'oneway' = ANY(tags) 
    AND 
    (SELECT Count(tags[i]) 
        FROM generate_subscripts(tags, 1) AS i 
        WHERE tags[i]='oneway')  > 1