我的表结构为
Tran_ID | total_amt | tran_date
我需要查找过去30天交易中产生的总收入。
我使用下面提到的查询但它既没有给出任何结果也没有任何错误。
select sum(total_amt)
from Transactions
having tran_date between max(tran_date)-30 and max(tran_date)
答案 0 :(得分:1)
您应该使用where子句来进行过滤。试试这个:
select sum(a.total_amt)
from Transactions a inner join (select max(tran_date) as max_trans_date from Transactions) b
on (a.tran_date between dateadd(DD,-30,b.max_tran_date) and b.max_tran_date);
答案 1 :(得分:0)
使用子查询。
SELECT sum(total_amt) as total from Transactions as a left join
(SELECT 'a' as gr, max(tran_date) as dmax, max(tran_date)-30 as dmin
FROM Transactions) as b
on a.tran_date <=b.dmax and a.tran_date>= b.dmin
where not isnull(b.dmax)
group by b.gr