查询计算行的总和(最近30天)

时间:2013-12-11 22:07:22

标签: mysql sql

我有这张表p_payments。该表格包含payment_amountpayment_statuscreatedtime列:

p_payments
____________________________
payment_status      varchar(25)
payment_amount      decimal(7,2)
createdtime         datetime

如何创建一个能够计算过去30天收入总和WHERE payment_status = completed的查询?

我的表

payments_status     payment_amount     createdtime
----------------------------------------------------------
Completed               1.00           2013-09-29 21:45:02
Denied                  2.00
Failed                  1.50
... etc

2 个答案:

答案 0 :(得分:3)

SELECT Sum(payment_amount) 
FROM   p_payments 
WHERE  payments_status = 'completed' 
       AND createdtime >= Date_Sub(Curdate(), INTERVAL 30 day) 

答案 1 :(得分:1)

SELECT SUM( p.`payment_amount` ) AS `total_payments`
FROM `payments` p
WHERE DATEDIFF(NOW(), p.createdtime) <= 30
  AND p.payment_status = 'Completed'