你需要一个左外连接。最简单的方法(IMO)是使用子查询分解,AKA 一个公共表表达式,来提供范围信息,然后将其连接到您的产品表:
with ranges as (
select 0 as min_price, 5000 as max_price, ' 0-5k' as score_range from dual
union all select 5000, 10000, '5-10k' from dual
union all select 10000, 20000, '10-20k' from dual
union all select 20000, 40000, '20-40k' from dual
union all select 40000, 80000, '40-80k' from dual
union all select 80000, 999000, '80-999k' from dual
)
select r.score_range, count(publicsellingprice) as number_of_occurences
from ranges r
left join product p on p.publicsellingprice between r.min_price and r.max_price
group by r.score_range, r.min_price
order by r.min_price;
但是,使用between
可能不会给您想要的结果;恰好在边界上的东西,例如在哪里publicsellingprice
,5000
将被计入两个桶中。您可以调整 CTE 中的最低/最高价格以给出一个上限(例如4999.99
),或者以不同的方式对它们进行比较:
with ranges as (
select 0 as min_price, 5000 as max_price, ' 0-5k' as score_range from dual
union all select 5000, 10000, '5-10k' from dual
union all select 10000, 20000, '10-20k' from dual
union all select 20000, 40000, '20-40k' from dual
union all select 40000, 80000, '40-80k' from dual
union all select 80000, 999000, '80-999k' from dual
)
select r.score_range, count(publicsellingprice) as number_of_occurences
from ranges r
left join product p on p.publicsellingprice >= r.min_price
and p.publicsellingprice < r.max_price
group by r.score_range, r.min_price
order by r.min_price;
在这两种情况下,我都将其包含min_price
在其中,group by
因此您也可以按此订购;否则,您将按字符串比较规则进行排序,这将使您的 5k 括号介于 40k 和 80k 之间。