我想选择所有购买了从(产品1到产品19)然后再购买产品20的产品的所有客户,这些交易必须在2018年1月1日之后发生。 -Productid列包含20个产品(产品1至产品20) 我需要一列中的第一组人,另一列中的另一组人,这将为我提供比例。
SELECT productid
,COUNT(DISTINCT(Primaryid))
,something
FROM transactions
WHERE Transactiondate >= '2018-01-01'
GROUP BY productid
以下是预期结果的示例:
答案 0 :(得分:0)
这将为您提供符合您条件的客户列表
使用IN
select Primaryid
from transactions
WHERE Transactiondate >= '2018-01-01'
and Primaryid in (select distinct Primaryid from transactions where productid < 20 and Transactiondate >= '2018-01-01')
and productid = 20
使用EXISTS
select t.Primaryid
from transactions t
WHERE t.Transactiondate >= '2018-01-01'
and exists (select t2.Primaryid from transactions t2 where t2.productid < 20 and t2.Transactiondate >= '2018-01-01' and t2.Primaryid = t.Primaryid)
and t.productid = 20
我不确定您的问题是什么比例,但是您应该可以从此处获取。这是一个刺。
select
t.productid
,total = (select count(*) from transactions tt where tt.productid = t.productid)
,ThenBoughtProduct = count(t.Primaryid)
from transactions t
WHERE t.Transactiondate >= '2018-01-01'
and exists (select t2.Primaryid from transactions t2 where t2.productid < 20 and t2.Transactiondate >= '2018-01-01' and t2.Primaryid = t.Primaryid)
and exists (select t3.Primaryid from transactions t3 where t3.productid = 20 and t3.Transactiondate >= '2018-01-01' and t3.Primaryid = t.Primaryid)
group by
t.productid
答案 1 :(得分:0)
我通常不希望按产品查看该产品,因为单个客户可能会被多次计数。
但是您似乎想要。因此,以下使用窗口函数获取每个产品的最小日期和产品20的最大日期。然后使用此信息获取所需的列:
select productid,
count(distinct primaryid) as num_clients,
count(distinct case when min_product_date < max_product20_date then primaryid) as num_clients_20_later
from (select t.*,
max(case when t.productid = 20 then t.transactiondate end) over (partition by t.primarykey) as max_product20_date,
min(t.transactiondate) over (partition by t.primarykey, t.productid) as min_product_date
from transactions t
where t.Transactiondate >= '2018-01-01'
) t
group by productid;