sql - In PostgreSQL, get a minimum value if there is none -
sorry if title did not match actual question. i'm not sure how phrase this.
in postgres, have users can @ station. stations numbered 1 5. have table users
, has column station
. if user @ station, station
value number of station, if not, null. here's how find number of users @ each station:
select station, count(users) users users station not null group station order station;
this yields:
station | users ---------+--------- 1 | 4 2 | 1 3 | 1
but that's not really true. there 0 users on station 4 , 5. how can address that? use query view calculate other things, need stations there. don't need table stations, far know: i'm not going use them anywhere else.
so how account unused stations? need make table them , reference stations table users table or there simpler way?
assuming have table stations
, can handle left join
:
select s.station, count(u.station) users stations s left join users u on s.station = u.station group s.station order s.station;
without such table, can use generate_series()
:
select s.station, count(u.station) users generate_series(1, 5) s(station) left join users u on s.station = u.station group s.station order s.station;
Comments
Post a Comment