mysql查询查找一段时间内的固定总和

时间:2013-02-07 05:33:54

标签: mysql sum period

我有一个包含以下列的mysql表

ORDER_ID 顾客ID 总金额 DATE_ADDED

现在,我想询问特定客户,了解客户是否在其订单历史记录的六个月内完成了超过或等于12000美元的订单金额。这段时间不是最近的。

有没有解决方案?

此致 Dipen

1 个答案:

答案 0 :(得分:1)

select sum(total_amount) >= 12000 over_12000
from mytable
where customer_id = nnn
and date_added between 'YYYY-MM-DD' and date_add('YYYY-MM-DD', interval 6 month)

将nnn替换为您感兴趣的6个月期间的特定客户ID和YYYY-MM-DD。

更新:

这将使用导致客户最后订单的6个月期间:

select sum(total_amount) >= 12000 over_1200
from mytable join (select max(date_added) last_date
                   from mytable
                   where customer_id = nnn) last
where customer_id = nnn
and date_added between last_date and date_sub(last_date, interval 6 month)

更新2:

select m1.date_added end_date, sum(m2.total_amount) >= 12000 
from mytable m1 join mytable m2 on m2.date_added between date_sub(m1.date_added, interval 6 month) and m1.date_added and m1.customer_id = m2.customer_id
where m1.customer_id = nnn
group by end_date
order by end_date