0

I am running PostgreSQL. I have a table called foo.Its content are:

city|number
'oo'|12
'ss'|11
'ss'|23
'oo'|11
'pp'|21

If I run a query like select count(city) from foo group by city having number<21 I will get

city|number
'oo'|2
'ss'|2

but I want the result to consider all the possible cases of city like this:

city|number
'oo'|2
'ss'|2
'pp'|0

How should the query look like?

5
  • What do you mean by "consider all the possible cases"? 21 is not < 21, which is why pp won't show up. Commented Feb 11, 2012 at 18:00
  • yeah but the requirement is it should consider the pp as well. Commented Feb 11, 2012 at 18:01
  • Then why not just use HAVING number <= 21? Commented Feb 11, 2012 at 18:02
  • yeah i know..but my requirement is as group by generate column values according to condition but i want the tables like second where it should consider the all the cases. I need know what should be query to generate the second one. Commented Feb 11, 2012 at 18:04
  • Shouldn't the result have only 1 "ss"? Like 'ss'|1?? Not to mention there is no ID in your table! Commented Feb 11, 2012 at 19:11

3 Answers 3

1
SELECT city, count(NULLIF(number < 21, false)) FROM cities GROUP BY city

should give you the desired result.

Sign up to request clarification or add additional context in comments.

Comments

0

This is could be solved with a left join:

select f1.city, count(f2.number) as total from foo as f1
left join foo as f2
on f1.cityId = f2.cityId and f1.number < 21
group by f1.city

Here is a working example

PS: Your example is wrong because ss should have a value of 1, not 2:

YOUR EXAMPLE         WHAT I THINK YOU REALLY WANT
city|number                   city|number
'oo'|2                        'oo'|2
'ss'|2                        'ss'|1
'pp'|0                        'pp'|0 

Hope this helps.

Comments

0

Think I misread the question first time, but try this:

select f1.city,count(*) from foo f1
where f1.city in (select f2.city from foo f2 where f2.number < 21)
group by f1.city
union 
select f3.city,0 from foo f3
where not exists (select * from foo f4 where f3.city=f4.city and f4.number < 21)
group by f3.city

The union splits the query so that the first half will identify which cities have an entry <21, and then count the number of occurrences of those cities.

The second half identifies cities which do not have an entry <21, and then counts them.

Comments

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.