和数的情况

时间:2018-10-31 14:55:50

标签: sql oracle max case-when

有一个额外的付款人,称为Workers comp,我正在通过在陈述时做案例来使其成为Workers Comp / Liability。我正在尝试返回一行。您的帮助将不胜感激。

这是我的查询:

select distinct
    case when payer.class like 'Workers%' 
        then 'Workers Comp/Liability'
        else Payer.class
    end as Payer,
    sum(Payment.payment_at) AS SumOfPmt
from Payer inner join Payer.payerid = Payment.payerid 
where payer.class like 'Workers%'
Group By payer.class      

结果:

Payer | SumOfPmt Workers Comp/Liability | 558.76 Workers Comp/Liability | 167036.41

我想要什么:

Payer | SumOfPmt Workers Comp/Liability | 167595.17

2 个答案:

答案 0 :(得分:2)

我将使用CASE子句重复相同的GROUP BY表达式:

select (case when p.class like 'Workers%' 
             then 'Workers Comp/Liability'
             else p.class
        end) as Payer,
       sum(pay.payment_at) AS SumOfPmt
from Payer p inner join 
     Payment py
     on p.payerid = py.payerid 
where p.class like 'Workers%'
group by (case when p.class like 'Workers%' 
               then 'Workers Comp/Liability'
               else p.class
          end);

您不必使用DISTINCT,因为它有GROUP BY

答案 1 :(得分:2)

这将是查询的一种简单形式:

select 'Workers Comp/Liability' as Payer,
       sum(pm.payment_at) AS SumOfPmt
from Payer py inner join
     Payment pm
     on py.payerid = pm.payerid 
where py.class like 'Workers%';

您的WHERE子句和CASE表达式在做同样的事情。只需一个。