Skip to content
Advertisement

Calculating a plug/balance in SQL

My current table has a few accounts which always have minimal values (example, X & Y for actual and AA, BB, CC & DD for plan) in current table. Accounts with minimal values can extend beyond these accounts. I need to categorize such accounts into proxy account called “balance” which would always be [final-(abc+def+ghi)](please refer to Expected table). I’m trying it difficult to construct this in SQL using sum (case when account not in ('abc','def','ghi').

Current tableand Expected results

Sample dataset here: http://sqlfiddle.com/#!9/114cfe/1

SQL attempt

select year, month, type,

case when accounts in 'abc' then 'abc'
case when accounts in 'def' then 'def'
case when accounts in 'ghi' then 'ghi'
case when accounts in 'final' then 'final'
else 'balance'
end as account_2
,
(
(case when accounts in ('abc','def','ghi','final') then sum(amount)
else 
(
(case when accounts in ('final') then sum(amount))-
sum(case when accounts in ('abc','def','ghi') then sum(amount) else 0)))
)

Advertisement

Answer

I think it would be easier to split it into two steps. Change the values in one step and group the rows in another.

SELECT year, month, type, account_2, SUM(amount) AS amount_2
FROM (
    SELECT year, month, type, amount,
        CASE WHEN accounts IN ('abc', 'def', 'ghi', 'final') THEN accounts 
        ELSE 'balance' END AS account_2
    FROM someTable
) AS tmp
GROUP BY year, month, type, account_2
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement