samuel west
samuel west

Reputation: 23

how could I subtract the sum of one table from the sum of another?

I am trying to build a program in which you enter date parameters and the sum of all the values in the 'cost' column which lie between the 2 dates entered are displayed.

I have got this part to work however the part I'm not sure how to do is to do the same operation on another table and then subtract one sum from the other. The purpose of this is to see the cash flow of a business. Here is the query I have so far:

datechoice1 = input('date from (formtat YYYY-MM-DD): ')
datechoice2 = input('date to (formtat YYYY-MM-DD): ')
c.execute("""SELECT SUM(cost) as sum_cost
          FROM outflows1
          where date between ? and ?
          """,
          (datechoice1, datechoice2)
          )

Essentially what I need help with is getting this query to select the sum from a table called 'outflows' which lies within the same date as entered in the query then the sum from the outflows table is taken away from the sum of the inflow table and this value is printed.

Upvotes: 0

Views: 102

Answers (1)

Benjamin McKay
Benjamin McKay

Reputation: 187

After you execute your query you can grab the results with:

c.fetchall() 

which will give you a list of results (a list of one item in your case, the SUM).

You can store this in a variable, and also the result of the query of your second table:

c.execute("""SELECT SUM(cost) as sum_cost
      FROM outflows1
      where date between ? and ?
      """,
      (datechoice1, datechoice2)
      )
result_one = c.fetchall()[0]
c.execute("""SOME OTHER QUERY HERE""")
result_two = c.fetchall()[0]
difference = result_one - result_two

Note that I index both the fetchall statements with [0] to grab the one element that should be returned by the SQL SUM.

Upvotes: 1

Related Questions