如何根据Oracle SQL中的一系列值检索值的数量

时间:2016-05-16 00:23:38

标签: sql oracle oracle11g

我想要一些Oracle SQL的帮助。让我们假设以下示例包含两个表:

enter image description here

根据盒子的大小,有一种方法可以知道每个范围内有多少个盒子:

Lib

我正在尝试以下句子,但它不能正常工作:

 Small   3 
 Medium  1
 Large   1

2 个答案:

答案 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