将一个变量中的不同值组合在一起

时间:2019-01-15 15:33:24

标签: sql group-by

是否可以将一个字段中的多个值组合在一起?例如,在“帐户”中,他们的合同类型为P,S,O。我需要将合同金额S和O求和,然后单独保留P。

我尝试过:

select Contract_ID, Case when contract_type in ('S', 'O')then sum(to_char(nvl(contract_amount,0), '000000.99' )) when contract_type = 'P' then sum(to_char(nvl(contract_amount,0), '000000.99' ))End as Contract_Amount

sum (Case when contract_type in ('S', 'O') then to_char(nvl(contract_hours,0), '000000.99')) when contract_type = 'P' then to_char(nvl(contract_hours,0), '000000.99')) End as Contract_Hours

from Contract group by Contract_id Contract_type

2 个答案:

答案 0 :(得分:0)

您要使用条件聚合。 casesum()的参数。像这样:

select Contract_ID,
       sum(Case when contract_type in ('S', 'O') then contract_amount 
           End) as Contract_Amount,
       sum(Case when contract_type in ('S', 'O') then contract_hours
           End) as Contract_hours
from Contract
group by Contract_id;

答案 1 :(得分:0)

在两种情况下,您需要使用UNION:

select t.* from (
  select ContractID, ContractAmount, ContractHours from Contract c
    where not exists (
      select 1 from Contract where 
        ContractID = c.ContractID and ContractType <> c.ContractType 
        and ContractType in ('O', 'S') and c.ContractType in ('O', 'S')
    )
  union
  select t.ContractID, SUM(t.ContractAmount), SUM(t.ContractHours) from (
    select * from Contract c
    where exists (
      select 1 from Contract where 
        ContractID = c.ContractID and ContractType <> c.ContractType 
        and ContractType in ('O', 'S') and c.ContractType in ('O', 'S')
    )
  ) t
  group by t.ContractID
) t
order by t.ContractID desc