我想要一些Oracle SQL的帮助。让我们假设以下示例包含两个表:
根据盒子的大小,有一种方法可以知道每个范围内有多少个盒子:
Lib
我正在尝试以下句子,但它不能正常工作:
Small 3
Medium 1
Large 1
答案 0 :(得分:3)
您应该将尺寸表修改为具有最小和最大尺寸:
alter table sizes add minsize number;
alter table sizes add maxsize int;
update sizes
set minsize = CAST(SUBSTR(range, 1, INSTR(range, '-') - 1 as number),
maxsize = CAST(SUBSTR(range, INSTR(range, '-') + 1) as number;
然后使用常规join
:
select s.range, count(*)
from packets p left join
sizes s
on p.size between s.minsize and s.maxsize
group by s.range
order by max(s.minsize);
您可以使用CTE执行相同的操作,但修复表格更好:
with s as (
select s.*,
CAST(SUBSTR(range, 1, INSTR(range, '-') - 1 as number) as minsize,
CAST(SUBSTR(range, INSTR(range, '-') + 1) as maxsize
from sizes
)
select s.range, count(*)
from packets p left join
s
on p.size between s.minsize and s.maxsize
group by s.range
order by max(s.minsize);
答案 1 :(得分:0)
select nvl(s.description,'UNKNOWN'),count(*)
from packets p left join s
on p.size between to_number(regexp_substr(s.range,'^[^-]+'))
and to_number(regexp_substr(s.range,'[^-]+$'))
group by s.description