从两个sql查询中减去多行

时间:2014-09-24 17:08:16

标签: sql postgresql

我创建了一个投注数据库,我正在努力确定谁是最好和最差的投注者。我决定这样做的最简单方法是获取用户的奖金总额,然后减去他们下注的金额

我的第一个SQL查询是

SELECT fromuser,SUM(itemsgiven::int)
FROM transactions
WHERE transtype='Bet Placed'
GROUP BY fromuser
ORDER BY 2 DESC

返回此

fromuser    sum
15228328    2689
13896406    2634
55954103    308
37460340    64
66589399    62

然后我的第二个问题是确定总奖金

SELECT touser,SUM(itemsgiven::float)
FROM transactions
WHERE transtype='Bet Won'
GROUP BY touser
ORDER BY 2 DESC

返回此

touser      sum
15228328    4387.515
55954103    152.295
13896406    120.285
66589399    71.28
37460340    56.925

我的问题是结合这些查询的最佳方式是什么,所以我可以有两列,一列是用户ID,另一列是总奖金(或者是失败)。我查了一些例子,但是让我失望的部分是你如何确定当你减去你只从相同用户ID中减去的两个总和时。

编辑:我正在使用postgresql

3 个答案:

答案 0 :(得分:1)

您可以使用此查询:

SELECT usr, SUM(subtotal) AS total
FROM (
  SELECT   fromuser AS usr, SUM(itemsgiven::int) AS subtotal
  FROM     transactions
  WHERE    transtype='Bet Placed'
  GROUP BY fromuser

  UNION ALL

  SELECT   touser AS usr, -1*SUM(itemsgiven::float) AS subtotal
  FROM     transactions
  WHERE    transtype='Bet Won'
  GROUP BY touser
) s
GROUP BY usr
ORDER BY 2 DESC

你确定itemsgiven :: int然后itemsgiven :: float?

答案 1 :(得分:0)

您可以使用UNION

执行此操作
 SELECT user_id, SUM(itemsgiven) as total_itemsgiven
 FROM
 (
   SELECT fromuser user_id, - itemsgiven::int itemsgiven
   FROM transactions
   WHERE 'Bet Placed' 
   UNION
   SELECT touser user_id, itemsgiven::int itemsgiven
   FROM transactions
   WHERE 'Bet Won'

 ) t
 GROUP BY user_id 
 ORDER BY 2 DESC

答案 2 :(得分:0)

您可以使用UNION

SELECT * FROM 
(SELECT fromuser as a,SUM(itemsgiven::numeric) as b
FROM transactions
WHERE transtype='Bet Placed'
GROUP BY fromuser
UNION 
SELECT touser as a,SUM(itemsgiven::numeric) as b
FROM transactions
WHERE transtype='Bet Won'
GROUP BY touser
) c
ORDER BY c.b DESC