合并一行中的多行acc。以SQL为条件

时间:2017-02-28 09:33:19

标签: sql

在SQL中我有一个查询。此查询用于查找员工的财务,管理和FYI错误。这些是不同类型的错误。

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 ,
case when c_errtype = 'FINANCIAL' then SUM(i_errcount) else 0 End/  sum( i_errcount ) as  financial_percent ,
case when c_errtype = 'ADMINISTRATIVE' then SUM(i_errcount) else 0 End/ sum( i_errcount)as administrative_percent,
case when c_errtype = 'FYI' then SUM(i_errcount) else 0 End /sum( i_errcount ) as FYI_percent
from    EL_Error_Mst
group by i_empid,c_errtype

我得到的结果如下:

i_empid claims_audited  total_errors    financial_errors    administrative_errors   FYI_errors  financial_percent   administrative_percent  FYI_percent
13  1   1   0   1   0   0.000000    1.000000    0.000000
341 1   1   0   1   0   0.000000    1.000000    0.000000
665 2   2   0   2   0   0.000000    1.000000    0.000000
341 1   1   1   0   0   1.000000    0.000000    0.000000

但我想为每位员工单行。我怎么能得到这个呢?

2 个答案:

答案 0 :(得分:1)

select  date,
        emp_id,
        examiner_name,
        sum( claims_audited ) as claims_audited,
        sum( errorCount ) as total_errors,
        sum( case when error_type = 'FINANCIAL' then 1 else 0 end ) as financial_errors,
        sum( case when error_type = 'ADMINISTRATIVE' then 1 else 0 end ) as administrative_errors,
        financial_errors / total_errors as financial_percent,
        administrative_errors/ total_errors as financial_percent
from    table_name
group by date,
        emp_id,
        examiner_name

答案 1 :(得分:0)

看起来你已经从最初的帖子中显着地编辑了你的问题,所以这是一个全新的答案。

您可能需要考虑以下几点:

  • 如果有任何员工有多种错误类型,那么您当前的查询将返回每i_empid个多行,因为您按c_errtype进行分组
  • 如果要计算百分比而不必在语句时重复大小写,则可以嵌套初始聚合,然后根据结果运行计算
  • 对于您可能希望转换为浮动的百分比,以便它不会将其舍入为整数

这是一个我认为可以获得你的想法的查询:

select  a.*,
        cast( financial_errors as float ) / total_errors as  financial_percent ,
        cast( administrative_errors as float ) / total_errors as administrative_percent,
        cast( FYI_errors as float) / total_errors as FYI_percent
from    (
          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
        ) as a

SQL Fiddle here