我不确定这是否可行....但是,如果之前没有数据,我是否可以为01-01-16 - 12/31/16提取数据。因此,如果他们在01-01-16之前购买,我不希望看到任何数据。基本上我正在努力寻找2016年的新客户。因此,在下面的示例中,John不会提取任何数据。
Name | Item # | Qty | Purch Date |
-----------+---------+-----+------------+
John | 12 | 7 | 2016-01-05 |
John | 22 | 14 | 2011-01-06 |
John | 11 | 9 | 2013-02-05 |
在这个例子中,它将拉动所有3。
Name | Item # | Qty | Purch Date |
-----------+---------+-----+------------+
John | 12 | 7 | 2016-01-05 |
John | 22 | 14 | 2016-01-06 |
John | 11 | 9 | 2016-02-05 |
答案 0 :(得分:1)
使用FIRST_VALUE
函数获取每个名称的第一个购买日期,并检查它是否在预期的日期范围内。
select name,item,qty,purch_date
from (
select t.*,
first_value(purch_date) over(partition by name order by purch_date) as first_purchase_date
from tablename t
) x
where first_purchase_date>='2016-01-01' and first_purchase_date<='2016-12-31'
--add a filter condition for purch_date if needed
答案 1 :(得分:1)
基于标量子查询的标准SQL解决方案:
select * from tab as t1
where purch_date between '2016-01-01' and '2016-12-31' -- purchase in 2016
and not exists -- but no purchase by the same customer in a previous year
( select * from tab as t2
where t1.name = t2.name
and t2.purch_date < '2016-01-01'
)
答案 2 :(得分:1)
我倾向于使用min()
作为窗函数:
select t.*
from (select t.*, min(purch_date) over (partition by name) as min_purch_date
from t
) t
where min_purchase_date >= '2016-01-01' and min_purchase_date < '2017-01-01';
如果您在2016年只想要新客户,但不需要详细信息:
select t.name
from t
group by t.name
having min(purchase_date) >= '2016-01-01' and min(purchase_date) < '2017-01-01';