I need a SQL query to list all the customers who have joined in last 6 months.
This is my SQL for that.
select
c.company_name,
c.phone1,
c.sprovince,
c.scountry,
sum(order_total_amount) as amt_sold,
max(o.order_date) as last_order_date,
customersince
from
tbl_company c
join
tbl_order o
on c.companyid = o.company_id
where
c.companytype like 'Customer'
and
(PERIOD_DIFF(c.customersince,curdate())<6)
group by company_name
order by amt_sold desc
Now I need one more or condition so that if there is null in customersince column then I should check the first order of the customer. If it is in last 6 months I should display that user also.
order_date is available in tbl_order table. The first order of the customer is min(order_date) group by customer_id
How can I do this?
Note the double condition on
customersince: one in theWHEREclause, another one in theHAVINGclause.If you have an index on
tbl_customer (customersince), this index will be used to filter the appropriate records early (and fine-filter them later).