2016-02-26 28 views
0

我有一个客户订单表,该表类似于下面:检查特定的ID的出现一行之前在表

order_id | customer_id | date | ... 
----------------------------------------- 
    583   192  2015-05-01 ... 
    734   143  2015-06-04 ... 
    801   455  2015-07-02 ... 
    ...   ...   ...  ... 

我想找到我多少新客户获得在特定的月份 。通过查询上面的订单表并找到当月出现但在该月之前没有出现的值(在该月之后没有问题),可以找到新客户。我正在寻找新的customer_id的第一个实例。

有没有办法在一个SQL语句中做到这一点?我可以做类似下面我想:

  • 通过查询使用LIKE YYYY-MM-%
  • 检查表与customer_id实例较小order_id(按理说一个较小的数据库得到了一个月的所有order_idDISTINCT customer_idorder_id将早期命令)
  • 如果找到,则跳过
  • 如果没有找到,递增计数器
+0

哪个db引擎? – user2407394

+0

你想要独特的用户,你不需要循环所有的结果只是使用group by并获得唯一的结果。同样,你只是数它们,所以如果你计算第一个或后一个数,那么它确实没有什么区别,只需要计数独特的数。 –

回答

1

假设date_From是你的起始日期和date_To是周期的最后一天,你能做到这一点是这样的:

select distinct T1.customer_id 
from your_table as T1 
    left outer join your_Table as T2 on 
     T1.customer_id = T2.customer_id and T2.date < date_From 
where 
    T1.date <= date_To 
    and T1.date >= date_From 
    and T2.customer_id is null 

这里您的日期,并检查之前,使用相同的customer_id和日期加入到同一个表中加入无结果(按T2.customer_id is null)确保您的customer_id首次按您的期限顺序出现,而不是更早。

1

这将会列出你的新客户在一月2016

select customer_id,order_id from customer c 
where MONTHNAME(date) = 'January' and YEAR(date) = 2016 
    and date >= 
(select min(date) mindate from customer c1 
where c.customer_id = c1.customer_id 
having MONTH(c.date) <> MONTH(c1.mindate) or YEAR(c.date) <> YEAR(c1. 
mindate)); 
1

你不需要的order_id,如果你需要统计客户。所有你需要的是customer_id和date:

select count(*) from 
    (select min(date) as first_contact, customer_id 
     from the_table 
     group by customer_id) new_customers 
where new_customers.first_contact > start_of_the_month 
    and new_customers.first_contact < end_of_the_month 
相关问题