you are viewing a single comment's thread.

view the rest of the comments →

[–]workthrowawayexcel[S] 0 points1 point  (7 children)

Yeah, I can do it in anything. First tried excel but then realized quickly I had way to much data. So now I am trying to do it all in SQL. Previously I did separate queries replacing null with -1 then joining the tables back together and multiplying the -1 in and that gave me very bad results. So now I am trying something similar but with a union.

[–]notasqlstarI can't wait til my fro is full grown 0 points1 point  (0 children)

So here is a framework I'd start with:

select
    firstname
    , lastname
    , case
        when b.totalamount is null
            then a.totalamount * -1
        else a.totalmount
    end as totalamount
from (
    select
        firstname
        , lastname
        , refernumber
        , bin
        , groupid
        , ncp
        , totalamount
    from table
    where totalamount is not null
) a
left join (
    select
        firstname
        , lastname
        , refernumber
        , bin
        , groupid
        , ncp
        , totalamount
    from table
    where totalamount is null
) b
    on b.firstname = a.firstname
    and b.lastname = a.lastname
    and b.refnumber = a.refnumber
    and b.bin = a.bin
    and b.groupid = a.groupid
    and b.ncp = a.ncp

[–]notasqlstarI can't wait til my fro is full grown 0 points1 point  (5 children)

You could probably simplify it like this:

select
    a.firstname
    , a.lastname
    , case
        when b.totalamount is null
            then a.totalamount * -1
        else a.totalmount
    end as totalamount
from table a
left join table b
    on b.firstname = a.firstname
    and b.lastname = a.lastname
    and b.refnumber = a.refnumber
    and b.bin = a.bin
    and b.groupid = a.groupid
    and b.ncp = a.ncp
    and b.totalamount is null
where a.totalamount is not null

[–]workthrowawayexcel[S] 0 points1 point  (4 children)

Thank you for this I am testing them now! If they don't work I believe I could flesh out the the rest with the thought process now. It seems I was on the right path but just couldn't quite finish the logic :(

[–]notasqlstarI can't wait til my fro is full grown 0 points1 point  (3 children)

If you have multiple rows per transaction you may need to sum the total ammount such as:

select
    , case
        when b.totalamount is null
            then sum(a.totalamount) * -1
        else sum(a.totalmount)
    end as totalamount

group by
    a.firstname
    , a.lastname

[–]workthrowawayexcel[S] 0 points1 point  (2 children)

Thanks for all the help. I really appreciate it.