title: Subtracting multiple rows from two sql queries
body: <p>I have created a betting database and I am trying to determine who are the best and worst betters. The easiest way I determined to do this is get the sum of the winnings by a user and subtract that by the sum amount they have bet</p>
  
  <p>My first SQL query is </p>
  
  <pre><code>SELECT fromuser,SUM(itemsgiven::int)
  FROM transactions
  WHERE transtype='Bet Placed'
  GROUP BY fromuser
  ORDER BY 2 DESC
  </code></pre>
  
  <p>Which returns this</p>
  
  <pre><code>fromuser    sum
  15228328    2689
  13896406    2634
  55954103    308
  37460340    64
  66589399    62
  </code></pre>
  
  <p>Then my second query is to determine the total winnings</p>
  
  <pre><code>SELECT touser,SUM(itemsgiven::float)
  FROM transactions
  WHERE transtype='Bet Won'
  GROUP BY touser
  ORDER BY 2 DESC
  </code></pre>
  
  <p>which returns this</p>
  
  <pre><code>touser      sum
  15228328    4387.515
  55954103    152.295
  13896406    120.285
  66589399    71.28
  37460340    56.925
  </code></pre>
  
  <p>My question is what is the best way to combine these queries so I can have a two columns, one with the user id and the other with their total winnings(or losings). I looked up some examples but the part that tripped me up is how do you make sure when you are subtracting the two sums that you only subtract from the same user id.</p>
  
  <p>EDIT: I am using postgresql</p>