简体   繁体   English

使用滞后功能

[英]Using Lag function

My current data pull is for customer in 2016. However i want to find out if a customers had a record before 2016. 我当前的数据来自2016年的客户。但是,我想了解客户在2016年之前是否有记录。


select ID,
       name, 
       date_enter,
       Date_leave,
       item_bought,
       lastitmebought =Lag(ID, 1) OVER (PARTITION BY Name ORDER BY Name , Date_leave)
from Customer 
where date between '01/01/2016' and '12/31/2016'

I know that my query is just looking at customers in 2016. Here is an example of what i would like to do: if a customer A comes in January 1, 2016 and had previously been in the store November,25,2015 i want my lag to give my the ID of the 2015 record as well, not just records found in 2016. 我知道我的查询只针对2016年的客户。这是我想做的一个例子:如果某个客户A于2016年1月1日到来,而以前曾在2015年11月25日入店,我想滞后也无法提供2015年记录的ID,而不仅仅是2016年的记录。

Thank you 谢谢

If you want to know if a customer has a record before 2016, I would suggest aggregation: 如果您想知道客户在2016年之前是否有记录,建议您汇总一下:

select c.id
from Customer c
group by c.id
having min(date_enter) < '2016-01-01';

If you want the ids of customers that are in both 2016 and 2015: 如果您想要2016年和2015年的客户ID:

select c.id
from Customer c
group by c.id
having max(date_enter) >= '2016-01-01' and
       sum(case when date_enter >= '2015-01-01' and date_enter < '2016-01-01' then 1 else 0 end) > 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM