2016-11-19 203 views
0

我这个例子,我需要得到基于优先级的工作/任务百分比的列表:聚合函数或GROUP BY子句中嵌套查询复杂

Priority Percentages 
----------------------- 
1   %25 
11   %10 

task_events表:

task_events_id time missing_info job_id task_index machine_id event_type user scheduling_class priority cpu_request memory_request disk_space_request different_machines_restriction 

job_id其任务可以在多行中,所以我创建了新的列task_events_id作为PK,用于嵌套选择以获取每个作业和任务的信号行。然后应用此结果来获得每项工作的优先级。我想出了这个查询。这里的主要概念是,我有11个优先级。优先考虑有很多工作。每个作业都被分配到一个优先级。

Select 
    tes.[priority], (tes.total_priority * 100/(select sum(tes.total_priority)from tes)) as [percentage] 
From 
    (select 
     [priority], count(*) as total_priority 
    from 
     task_events as t 
    inner join 
     (select 
       max(task_events_id) as maxid, 1 as total 
      from 
       task_events 
      group by 
       job_id, task_index) as te on t.task_events_id = te.maxid 
    group by 
     [priority]) as tes 
group by 
    tes.[priority] 

这最好的我想出了,但总的是越来越复杂,任何建议

与此查询我得到这个错误:

无效的对象名称TES“。

while it's put'tes.total_priority'on last group by。

+0

样本数据和预期的结果将真正帮助解释你想要做什么。例如,百分比是什么? –

+0

每个job_id,这里的每个工作都有优先权,我有11个优先级,每个优先级都有很多工作 – jou

回答

0

如果每个优先级,你想要的整体总量的百分之它,然后使用窗口功能:

select [priority], count(*) as total_priority, 
     count(*) * 1.0/sum(count(*)) over() as ratio 
from task_events t 
group by [priority]; 
+0

好吧,我只需要百分比来完成工作和任务。所以我认为它应该按工作分组。 – jou

0

其实你的查询只需要在最后group by额外领域的工作......添加tes.total_priority有.. 它没有工作,虽然 - 代码中删除

-- Code removed 

,但你可以通过删除inner join考虑这个简单的查询,并使用distinct代替

Select 
    tes.[priority], (tes.total_priority * 100.0/sum(tes.total_priority)) as [percentage] 
From 
    (select 
     [priority], count(*) as total_priority 
    from 
     (select 
      distinct [priority], job_id, task_index 
     from task_events) as t 
     ) as tes 
group by 
    tes.[priority], tes.total_priority 

或更多使用的窗函数

select 
    [priority], count(*) as total_priority, 
    count(*) * 100.0/sum(count(*)) over() as ratio 
from (select distinct [priority], job_id, task_index 
     from task_events) as t 
group by [priority]; 

,最后一个简单的一个,如果job_id你所需要的计算和task_index可以从子查询中删除..然后子查询可以删除通过替换count(*)count(distinct job_id) ..但结果可能会不同于以前的查询取决于数据和哪一个是正确的?依赖于真正想从这些数据来实现..它只是建议,但..

select 
    [priority], count(distinct job_id) as total_priority, 
    count(distinct job_id) * 100.0/sum(count(distinct job_id)) over() as ratio 
from task_events t 
group by [priority]; 
+0

好吧,让我们看看这个 – jou

+0

如果你添加tes.total_priority,它会给你100%的优先级。这就是为什么我没有在 – jou

+0

上加上它,最后2个查询有不同的答案,这让我担心哪一个可能是正确的。 – jou

相关问题