2017-02-28 45 views
0

在SQL中,我有一個查詢用於查找僱員犯的錯誤類型。員工可以犯的錯誤有3種類型 - 財務,行政和FYI錯誤。我使用group by子句與employeeid和錯誤類型,但是我想僅使用employeeid進行分組,但是在這種情況下,會拋出錯誤,因爲它包含在選擇列表中,因此必須將錯誤類型包含在組中。根據條件將由group by clause返回的行合併到單行中

select i_empid, 
    COUNT(i_empid) as claims_audited, 
    sum(i_errcount) as total_errors, 
    case 
     when c_errtype = 'FINANCIAL' 
      then SUM(i_errcount) 
     else 0 
     end as financial_errors, 
    case 
     when c_errtype = 'ADMINISTRATIVE' 
      then SUM(i_errcount) 
     else 0 
     end as administrative_errors, 
    case 
     when c_errtype = 'FYI' 
      then SUM(i_errcount) 
     else 0 
     end as FYI_errors 
from EL_Error_Mst 
group by i_empid, 
    c_errtype 

我得到的結果集是這樣的:

i_empid claims_audited total_errors financial_errors administrative_errors FYI_errors 
13   1    1     0      1    0  
341   1    1     0      1    0 
665   2    2     0      2    0 
341   1    1     1      0    0 

,但我想爲每一個給每個類型的錯誤由him.how提出我能得到這個員工單列?

+1

MySQL或SQL Server?請選擇一個。 – DavidG

+0

你的問題沒有多大意義。它看起來像提供你正在尋找的輸出。這裏是改善這個問題的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –

回答

0

您需要恢復情況和金額的訂單,並通過c_errtype刪除組:

select i_empid, 
count(i_empid) as claims_audited 
sum(case when c_errtype='FINANCIAL' then i_errcount else 0 end) as financial_errors, 
sum(case when c_errtype='ADMINISTRATIVE' then i_errcount else 0 end) as administrative_errors, 
sum(case when c_errtype='FYI' then i_errcount else 0 end) as fyi_errors 
from EL_Error_Mst 
group by i_empid 
+0

Iam得到錯誤。列'EL_Error_Mst.c_errtype'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 –

1

我覺得是由你如何試圖總結你的條件引起的您的錯誤。這個怎麼樣?

select i_empid, 
    count(i_empid) as claims_audited, 
    sum(i_errcount) as total_errors, 
    sum(case 
     when c_errtype = 'FINANCIAL' 
      then i_errcount 
     else 0 
     end) as financial_errors, 
    sum(case 
     when c_errtype = 'ADMINISTRATIVE' 
      then i_errcount 
     else 0 
     end) as administrative_errors, 
    sum(case 
     when c_errtype = 'FYI' 
      then i_errcount 
     else 0 
     end) as FYI_errors 
from EL_Error_Mst 
group by i_empid 
+0

仍然Iam得到相同的錯誤 –

+0

它的工作。感謝很多好友 –