[英]Oracle SQL: manipulating group
I have a simple query such as this 我有一个像这样的简单查询
select duration, host from Jobs
group by host;
i want it actually group by a pool of hosts which is something that needs to be defined at query time 我希望它实际上由主机池分组,这是在查询时需要定义的
for example, host01-10 would be pool1, host11-20 would be pool2, etc. 例如,host01-10将是pool1,host11-20将是pool2,依此类推。
at the moment, there isnt a field which says what pool it is in and but it needs to be derived from the host field. 目前,没有一个字段说明它在哪个池中,但是需要从宿主字段派生。
how do i achieve that? 我该如何实现? I want to be able to creation some sort of function on the slide to maniuplate the field so that it is group-able 我希望能够在幻灯片上创建某种功能来操纵该字段,以便它可以分组
def get_pool(host):
if get_hostnumber(host) < 10:
return 'pool1'
elif:
...
select duration, get_pool(host) from Jobs
group by get_pool(host);
In SQL, you don't need a function for this. 在SQL中,您不需要为此的功能。 I would suggest just using a case
expression: 我建议只使用一个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);
For your particular example, you could get away with: 对于您的特定示例,您可以摆脱:
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);
And, lest I forget, I you have a permanent mapping between hosts and their groups, then you should put a hosts
reference table in the database and have a second column for the group. 而且,以免忘记,您在主机及其组之间有一个永久的映射,那么您应该在数据库中放置一个hosts
引用表,并为该组添加第二列。 Then this query would simply use a join
, and any other query you write would have the same information. 然后,此查询将仅使用join
,并且您编写的任何其他查询将具有相同的信息。
You can use case when in select and in group by: 在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.