需要使用另一个表中的客户信息对一个表中的事务总计求和

时间:2014-08-25 19:35:49

标签: mysql sql

我花了最后一小时寻找可以用来实现的东西,但是我找不到我需要的东西。

我有两张桌子:TRANSACTIONS&客户

CUSTOMER
internal_id | name | email

TRANSACTIONS
internal_id | customer_id | transaction_date | total_amount

我想循环遍历所有客户,然后按月和年总结每个客户的总交易量。我认为这就像将select语句作为列添加到初始查询一样简单,但这显然不起作用:

不工作:

select customer.internal_id, 
(sum(total_amount) as 'total' from TRANSACTIONS where transactions.customer_id = customer.internal_id and transaction_date  >= DATE_SUB(NOW(),INTERVAL 1 month)), 
 (sum(total_amount) as 'total' from TRANSACTIONS where transactions.customer_id = customer.internal_id and transaction_date  >= DATE_SUB(NOW(),INTERVAL 1 year))
from CUSTOMER join TRANSACTIONS on CUSTOMER.internal_id = TRANSACTIONS.customer_id

基本上我希望输出看起来像这样:

CUSTOMER.name | TRANSACTIONS.total_amount_month | TRANSACTIONS.total_amount_year
ABC Company   | $335.00                         | $8900.34

单个查询是否可以实现?我使用PHP实现了多个查询,如果可能的话,只是为了性能而更喜欢单个查询。

谢谢!

1 个答案:

答案 0 :(得分:1)

SELECT c.name,
       SUM(IF(transaction_date >= DATE__SUB(NOW(), INTERVAL 1 MONTH), total_amount, 0) AS total_amount_month,
       SUM(total_amount) AS total_amount_year
FROM transactions AS t
JOIN customer AS c ON c.internal_id = t.customer_id
WHERE transaction_date >= DATE__SUB(NOW(), INTERVAL 1 YEAR
GROUP BY t.customer_id