1

I've found nothing about my problem. I have 2 tables like: range(pk, min, max) and user(name, value), I'll inner join and group by to have: for every range, every user, the sum of value (even when there is no result). Like :

range   name    value
0-10    test     2

0-10    test2    8
0-10    test3    3

0-10    test4    7
0-20    test     0 ====> actualy, i don't get this line

0-20    test2    8
0-20    test3    3

0-20    test4    7

Actually my query is:

select cast(range.min AS CHARACTER VARYING) || '-' || cast(range.max AS CHARACTER VARYING)
    ,user.NAME
    ,count(*)
FROM range
INNER JOIN user ON user.value >= range.min
    AND user.value <= range.max
GROUP BY range.pk
    ,user.NAME
ORDER BY range.pk;

Does anyone have an idea to insert 0's when there is no result?

EDIT : My range is never NULL, i'll just add user name when he is not in range.

1 Answers1

1

This is a bit confusing because there is a table called user with duplicate names. So either this is not the user table (with one record per user) or we are not really interested in users here but in user names (and multiple users can have the same name).

Anyway: You want to count zero when the user doesn't match the range. This means you want to combine all users with all ranges and then count. Do this with a cross join.

select
  r.min || '-' || r.max as value_range,
  u.name as user_name,
  (
    select count(*) 
    from users u2 
    where u2.name = u.name 
    and u2.value between r.min and r.max
  ) as user_range_count
from range r
cross join (select distinct name from user) u
order by r.min, r.max, u.name;
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73