SQL查询以获取最近30天之前的记录(不是最近30天)

时间:2019-10-25 06:10:58

标签: mysql sql select intervals

我想找到我最近30天的值与之前最近30天的值的不同百分比。我已经有了最近30天的总值。如何获得前30天的总和?

这是用于选择最近30天总和的查询。

SELECT SUM(paymentAmount) as usd30day
FROM `tbl_pi_payment` 
WHERE currencyCode = 'USD' and renewalDate >= NOW() - INTERVAL 30 DAY

示例:今天是10月25日。 我有10月25日至9月26日的值总和。 现在我需要9月26日至8月25日的值之和

3 个答案:

答案 0 :(得分:2)

您可以在下面尝试-

SELECT SUM(case when renewalDate >= NOW() - INTERVAL 30 DAY paymentAmount else 0 end) as usd30day ,
SUM(case when renewalDate >= NOW() - INTERVAL 60 DAY and renewalDate < NOW() - INTERVAL 30 DAY paymentAmount else 0 end) as usd60day
FROM tbl_pi_payment
WHERE currencyCode = 'USD' 

答案 1 :(得分:1)

基于renewalDate

获取以前的交易
select sum(case when renewalDate >= NOW() - INTERVAL 30 DAY then paymentAmount else 0 end) as usd30day 
    , sum(case when datediff(now() - renewalDate) <= 30 then paymentAmount else 0 end) as usd30prevday 
from tbl_pi_payment 
where 
    currencyCode = 'USD' 

答案 2 :(得分:0)

SELECT datediff(NOW(), renewalDate) % 30 as every30day, SUM(paymentAmount) as usd30day
FROM `tbl_pi_payment`
WHERE currencyCode = 'USD' 
GROUP BY datediff(NOW(), renewalDate) % 30