我正试图找出编写查询的最佳方法,这将帮助我确定本月的新客户,但还有三个月前与我们进行过交易但本月才回来的老客户。
select customer_id
from(
select s.customer_id,
min(ss.tran_date) as customer_first_date,
max(ss.tran_date) as customer_last_date
from shipments s
left join shipment_stops ss on ss.customer_id = s.customer_id)
where date_trunc('month',customer_first_date) = date_trunc('month',now()) OR ?????
任何帮助或指向正确方向的信息将不胜感激。
非常感谢您。
最好
答案 0 :(得分:0)
您指的是最近一个月,因此请查看having
子句中的最新交易,然后再查看select
中的最早交易:
select s.customer_id,
(case when min(ss.tran_date) >= date_trunc('month', now())
then 'New'
else 'Existing'
end) as grouping
from shipments s left join
shipment_stops ss
on ss.customer_id = s.customer_id
group by s.customer_id
having max(ss.tran_date) >= date_trunc('month', now())
答案 1 :(得分:0)
使用子查询-选择3个月大的客户和当月客户,然后与当前月的3个月大客户进行左联接,如果两个客户都匹配,则为老客户,否则为新客户
with t1 as
( select s.* from from shipments s
left join shipment_stops ss on ss.customer_id = s.customer_id)
where date_trunc('month',customer_first_date)<= date_trunc('month',CURRENT_DATE - INTERVAL '3 months')
) , t2 as
(
select s.* from from shipments s
left join shipment_stops ss on ss.customer_id = s.customer_id)
where date_trunc('month',customer_first_date)>= date_trunc('month',now())
) select case when t2.customer_id=t1.customer_id then 'old customer'
else 'new customer who comes this month' end customer_status
left join t1
on t2.customer_id =t1.customer_id
答案 2 :(得分:0)
找到本月所有交易的客户(使用exists
子查询)并进行一些条件汇总以区分新客户和退货客户:
SELECT
customer_id
, CASE
WHEN prev_max_dt < (current_date - '3 month'::INTERVAL)
THEN 'Returning'
ELSE 'New'
END
FROM (
SELECT
ss.customer_id
, MAX(CASE
WHEN ss.tran_date < date_trunc('month', current_date) THEN ss.tran_date
END) AS prev_max_dt
FROM shipment_stops ss
WHERE EXISTS (
SELECT NULL
FROM shipment_stops
WHERE tran_date >= date_trunc('month', current_date)
AND customer_id = ss.customer_id
)
GROUP BY
ss.customer_id
) d