繁体   English   中英

Oracle SQL:操作组

[英]Oracle SQL: manipulating group

我有一个像这样的简单查询

select duration, host from Jobs
group by host;

我希望它实际上由主机池分组,这是在查询时需要定义的

例如,host01-10将是pool1,host11-20将是pool2,依此类推。

目前,没有一个字段说明它在哪个池中,但是需要从宿主字段派生。

我该如何实现? 我希望能够在幻灯片上创建某种功能来操纵该字段,以便它可以分组

def get_pool(host):
   if get_hostnumber(host) < 10:
        return 'pool1'
    elif:
        ...

select duration, get_pool(host) from Jobs
group by get_pool(host);

在SQL中,您不需要为此的功能。 我建议只使用一个case表达式:

select (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end) as hostgrp, sum(duration) as duration
from jobs
group by (case when host <= 'host10' then 'pool1'
             when host <= 'host20' then 'pool2'
             . . .
        end);

对于您的特定示例,您可以摆脱:

select 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10),
       sum(duration) as duration
from jobs
group by 'pool' || floor( (cast(substr(host, 5, 6) as number) + 1) / 10);

而且,以免忘记,您在主机及其组之间有一个永久的映射,那么您应该在数据库中放置一个hosts引用表,并为该组添加第二列。 然后,此查询将仅使用join ,并且您编写的任何其他查询将具有相同的信息。

在select和group by中时,可以使用用例:

select duration, (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2')
from Jobs
group by (case when host <10 then 'pool1' when host  between 10 and 19 then 'pool2');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM