0

I have Table:

stations (staion , phone , address)

AND

members (username , password , fullname , station)

I want to Station List , count username . So I wrote this query.

SELECT 
    stations.station as st,
    (
        SELECT COUNT(username) 
        FROM members 
        WHERE members.station = stations.station
    ) as co
FROM stations
GROUP BY stations.station
ORDER BY stations.station

It alerts (Error) :

'ERROR: subquery uses ungrouped column "stations.station" from outer query'

Please help me to get right data with PostgreSQL.

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260

3 Answers3

1

The proper solution is this:

SELECT 
stations.station as st,
(
    SELECT COUNT(username) 
    FROM members 
    WHERE members.station = ANY( array_agg( stations.station ) )
) as co
FROM stations
GROUP BY stations.station
ORDER BY stations.station
  • Yep, that worked for me! But according to https://stackoverflow.com/a/34627688/1676382 `=ANY` is less likely to use an index. However, when I tried a solution using `IN array_to_string(array_agg(stations.station), ',')` as a template, it still didn't didn't use an index for me :( – Opux Sep 12 '18 at 14:26
0

Try this

select stations.station as st,count(username) as co 
from member left join stations on member.station=stations.station 
group by stations.station 
order by stations.station;
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
amudhan3093
  • 740
  • 9
  • 17
0

simple answer without join is:

SELECT  stations.station, COUNT(username)
FROM stations, members
WHERE members.station = stations.station
GROUP BY stations.station
ORDER BY stations.station
Farvardin
  • 5,336
  • 5
  • 33
  • 54