根据多个变量查找平均值

时间:2017-01-27 10:36:53

标签: mysql sql

我必须找到2012年每个月每种付款类型至少使用一次的帐户所花费的平均金额。我使用的表格有以下交易:account_id,purchase_date,payment_type和amount 游戏:account_id,game_id和game_date

到目前为止我已经

 SELECT SUM(amount) FROM Transactions
 WHERE DATE (purchase_date) BETWEEN '2012-01-01' AND '2012-12-31'
 AND account_id in (SELECT account_id FROM Games WHERE (Games.game_date) 
 BETWEEN '2012-01-01' AND '2012-12-31') GROUP BY payment_type; 

我不知道如何进一步推动这一进展。到目前为止我的结果只显示一列,所以我甚至不知道哪种付款方式是多少。如何显示这些付款类型,然后根据每月进行的交易数量对其进行平均?

修改

所以我有

 SELECT payment_type, AVG(amount) FROM Transactions
 WHERE DATE (purchase_date) BETWEEN '2012-01-01' AND '2012-12-31'
 AND account_id in (SELECT account_id FROM Games WHERE (Games.game_date) 
 BETWEEN '2012-01-01' AND '2012-12-31') GROUP BY payment_type; 

显示了2012年每种付款方式的平均花费,我只需按月对其进行排序。

1 个答案:

答案 0 :(得分:1)

获得payment_type的总和(使用查询作为表格)

   select avg(tot)  from (
      SELECT payment_type, SUM(amount)  as tot FROM Transactions
       WHERE DATE (purchase_date) BETWEEN '2012-01-01' AND '2012-12-31'
       AND account_id in (SELECT account_id FROM Games WHERE (Games.game_date) 
       BETWEEN '2012-01-01' AND '2012-12-31') GROUP BY payment_type
   ) t 

或者你可能只需要

 SELECT payment_type, SUM(amount), AVG(amount)   
 FROM Transactions
 WHERE DATE (purchase_date) BETWEEN '2012-01-01' AND '2012-12-31'
 AND account_id in (SELECT account_id FROM Games WHERE (Games.game_date) 
      BETWEEN '2012-01-01' AND '2012-12-31') 
 GROUP BY payment_type