我是SQL初学者。我很难找到这个问题的答案
对于在2006年1月1日下订单的每个customer_id,他们的历史记录(在2006年1月1日之前)是第一个和最后一个日期?
我尝试使用子查询来解决它。但是我不知道如何查找1月1日之前的第一个和最后一个订单日期。
表A的列:
customer_id
order_id
order_date
revenue
product_id
表B的列:
product_id
category_id
SELECT customer_id, order_date FROM A
(
SELECT customer_id FROM A
WHERE order_date = ‘2006-01-01’
)
WHERE ...
答案 0 :(得分:0)
您可以在集合函数中使用条件:
SELECT customer_id, MIN(order_date) AS first, MAX(order_date) AS last FROM A
WHERE customer_id IN (SELECT customer_id FROM A WHERE order_date = ‘2006-01-01’) AND order_date < '2006-01-01'
GROUP BY customer_id;
答案 1 :(得分:0)
实际上有两个子查询。首先是“ 对于在2006年1月1日下订单的每个customer_id ”,其次是“ 其历史记录(2006年1月1日之前)的第一个和最后一个订购日期”
所以,首先:
select customer_id from A where order_date = '2006-01-01';
第二:
select customer_id, min(order_date) as first_date, max(order_date) as last_date
from A
where order_date < '2006-01-01' group by customer_id;
最后,您只需要从第一个子查询中存在的第二个子查询中获得那些客户:
select customer_id, min(order_date) as first_date, max(order_date) as last_date
from A as t1
where
order_date < '2006-01-01' and
customer_id in (
select customer_id from A where order_date = '2006-01-01')
group by customer_id;
或者可能更有效:
select customer_id, min(order_date) as first_date, max(order_date) as last_date
from A as t1
where
order_date < '2006-01-01' and
exists (
select 1 from A as t2
where t1.customer_id = t2.customer_id and t2.order_date = '2006-01-01')
group by customer_id;