Skip to content
Advertisement

Calculating values from two tables where one has key in header and one has it in column values

I have a simple problem that I dont know how to solve in sql.

I have two tables, cost :

     a |  b    |  c
-------+-------+---------------
 31.99 | 14.12 | 133.1

second table: income

Party | sum
------+--------
  A   |  90
  B   |  12
  C   |  70

Now i want to get a result that substract for each party A, B, C the income-cost and finds the net value. I cannot compare the column header to column value. I am quite new to this, so I am struggling quite a lot. There should be really easy way of doing this.

I created the ‘cost’ table by

 SELECT sum(A) as A, sum(B) as B, sum(C)  as C FROM mytable;

may be there is clever way of creating this table in the same formate as income table that would make it easier to compare? I will appreciate any suggeestion on any of the two fronts. Thanks a lot!

Advertisement

Answer

You can compare, using case:

select party,
       cost - (case when party = 'a' then a
                    when party = 'b' then b
                    when party = 'c' then c
               else 0 end)
from cost c cross join
     income i
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement