SQL-计算最近7天的金额

时间:2018-11-20 12:15:00

标签: mysql sql

我正在尝试编写sql,我可以在每个DATE使用groupBy返回每天的金额。

我的字段是金额和transaction_date,我的sql是:

select id,    
Amount as amount,    
transactionDate as transaction_date      
from transaction    
WHERE transactionDate IN (SELECT DISTINCT TOP 7 transactionDate from transaction
order by transactionDate)

因此,我的sql语法错误,无法弄清楚下一步该怎么做。

3 个答案:

答案 0 :(得分:0)

使用汇总和分组依据

select transactionDate     
sum(Amount) as amount,    
from transaction  
where transactionDate>=cast(now()-INTERVAL -7 DAY as date) and transactionDate<cast(now() as date)
group by transactionDate 

答案 1 :(得分:0)

尝试以下方式

select date(transactionDate) as transaction_date  
sum(Amount) as amount           
from transaction    
WHERE date(transactionDate)>=  DATE_ADD(current_date(),INTERVAL -7 DAY)
group by date(transactionDate)

BTW Top是非mysql的sql服务器关键字

答案 2 :(得分:-1)

谢谢大家,给我一条可以走的路。我找到了解决方案。非常感谢。

 SELECT
 DATE(transaction_date) AS TransactionDate, SUM(amount) AS Amount
 FROM transaction
 WHERE type = 'spend'
 AND transaction_date>=  DATE_ADD(NOW(), INTERVAL -7 DAY)
 GROUP BY TransactionDate