我有两张表users
和select
jobs_done,
count(1) as number_of_users
from ( select
u.id,
count(*) as jobs_done
from jobs j
JOIN users u on j.user_id = u.id
group by u.id ) a
group by jobs_done
。
用户与作业具有一对多的关系。
我想将用户划分为jobs_done组。 换句话说,有多少用户做过1份工作,2份工作,3份工作等等 以下查询就是这样做的。但是,我想将已完成3个或更多作业的所有用户整合到一个组中。
这是我目前的查询
times_used number_of_users
1 255
2 100
3 30
4 10
5 9
当前输出:
times_used number_of_users
1 255
2 100
3+ 49
期望的输出:
{{1}}
答案 0 :(得分:2)
您可以使用case
表达式将值3+分组到一个大组中。这应该有效:
select
case
when jobs_done >= 3 then '3+'
else cast(jobs_done as varchar(5))
end as jobs_done,
count(1) as number_of_users
from (
select
u.id,
count(*) as jobs_done
from jobs j
join users u on j.user_id = u.id
group by u.id
) a
group by case when jobs_done >= 3 then '3+'
else cast(jobs_done as varchar(5))
end;
答案 1 :(得分:0)
你可以基本上把所有东西分组。这是一个简单的例子:
test=# SELECT CASE WHEN x < 4 THEN x::text ELSE '4+' END AS y,
count(*)
FROM generate_series(1, 10) AS x
GROUP BY y
ORDER BY 1;
y | count
----+-------
1 | 1
2 | 1
3 | 1
4+ | 7
(4 rows)