2016-11-19 140 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

相關問題