質問

I have a mysql table with following columns

order_id customer_id total_amount date_added

Now, i would like to make a query for a particular customer to know if the customer has made more than or equal to 12000$ amount of order over six months period of his/her order history. The period is not recent.

Is there any solution for this?

Regards, Dipen

役に立ちましたか?

解決

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)

Replace nnn with the particular customer ID, and YYYY-MM-DD with the start of the 6 month period that you're interested in.

UPDATE:

This will use the 6 month period leading up to the customer's last order:

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)

UPDATE 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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top