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.

0

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that worked for me! But according to 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 :(
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;

1 Comment

I think you mean left join
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

1 Comment

Although you are not writing the join world you are still doing a join

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.