根据条件将group by子句返回的行合并为单行

时间:2017-02-28 17:15:55

标签: sql

在SQL中,我有一个查询,用于查找员工所犯的错误类型。员工可以犯3种错误 - 财务,管理和FYI错误。我使用了groupid子句与employeeid和错误类型,但我只希望group by with employeeid,但在这种情况下,抛出错误,你必须在group by中包含错误类型,因为它包含在选择列表中。

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

但是我想为每个员工提供单行,以便为他提供每种类型的错误。我可以得到这个吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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