按子句分组,使用字段作为符号+-

时间:2018-09-26 16:24:50

标签: sql postgresql

我遇到以下情况(简化查询):

select split_part(field1,'_',1) as order_sign
    , odp.dr_id
    , sum(odp.use_count) as usecount
    , cost
from table1
    inner join table2 odp on .. = odp.dr_id
    inner join .. = ..
    ...
where 
    condition1 AND condition2 AND ..
    AND (split_part(field1,'_',1) in ('in', 'out'))
group by split_part(field1,'_',1), odp.dr_id, cost
order by odp.dr_id

我得到的结果是:

"in"  ;8;1;70
"in"  ;24;2;70
"out" ;27;1;70
"in"  ;32;3;70
"in"  ;38;2;70
"out" ;44;1;70
"in"  ;52;3;70
"out" ;57;1;70
"in"  ;58;1;70
"in"  ;79;1;70
"out" ;79;2;70
"out" ;96;2;70
"out" ;114;1;70
"out" ;117;1;70
"out" ;124;2;70
"out" ;228;1;70

如何使用“ in”作为“减号”,“ out”作为“加号”,以获得如下结果:

        8   ; -1 ;70)
        24  ; -2 ;70)
        27  ;  1 ;70)
        ...
        79  ;  (-1+2); 70
        ...
        228 ;  1; 70

使用postgresql吗?我想只使用SQL来获得结果。

1 个答案:

答案 0 :(得分:0)

我解决了,只是想了更多)

with mycte as (
    select split_part(field1,'_',1) as order_sign
        , odp.dr_id
        , sum(odp.use_count) as usecount
        , cost
    from table1
        inner join table2 odp on .. = odp.dr_id
        inner join .. = ..
        ...
    where 
        condition1 AND condition2 AND ..
        AND (split_part(field1,'_',1) in ('in', 'out'))
    group by split_part(field1,'_',1), odp.dr_id, cost
    order by odp.dr_id
)
select dr_id,  
    sum(
        CASE 
            WHEN order_sign = 'in' then 0-usecount
            ELSE usecount
        END

    ) AS signed_usecount
    ,cost
from mycte
group by dr_id, cost
order by dr_id

预期结果。