确定购买模式 SQL
Identify purchasing patterns SQL
我希望识别从我的商店购买了一系列产品的会员并保存他们的详细信息以供进一步分析。
我有兴趣确定购买苹果的会员 AND 他们是否 以前 购买过梨或橙子或葡萄或甜瓜。
我的交易数据如下:
根据以上数据,会员 1 购买了苹果 (4/4/2020),但在此之前没有购买一种或多种主要产品(梨或橙子或葡萄或甜瓜)。
然而,会员2也买了苹果,但在此之前他们也买了梨(02/22/2020),因此他们是感兴趣的会员。
理想情况下,如果条件匹配,输出将只是 MBR_ID 的一列和标题为 interest_y_n 的列,如果条件不匹配,则输出为 no。
对于如何解决此问题的任何指导,我将不胜感激。
如果有帮助,我正在使用 Netezza 作为数据库平台。
嗯。 . .这听起来像是聚合:
select mbr_id,
(case when sum(case when product = 'apples' then purchase_date end) >
sum(case when product in ('pears', 'oranges', 'grapes', 'melon') then purchase_date end)
then 1 else 0
end) as is_member_of_interest
from transactions t
group by mbr_id;
case
中的条件聚合将 "apple" 购买的最早日期与其他水果的较早日期进行比较。仅当苹果在其他苹果之后购买时,该值才为真。
您也可以使用 CTE。这是 demo.
with maxDate as
(select
mbr_id,
max(purchase_date) as mxDate
from test
where product = 'apples'
group by
mbr_id
),
minDate as
(
select
mbr_id,
min(purchase_date) as mnDate
from test
group by
mbr_id
),
inter_y as
(
select
t.mbr_id,
'y' as interest_y_n
from test t
join maxDate mx
on t.mbr_id = mx.mbr_id
join minDate mn
on t.mbr_id = mn.mbr_id
where purchase_date between mnDate and mxDate
and product in ('pears', 'oranges', 'grapes', 'melon')
)
select
distinct mbr_id,
'n' as interest_y_n
from test t
where not exists (select mbr_id from inter_y iy where t.mbr_id = iy.mbr_id)
union all
select *
from inter_y
输出:
*----------------------*
| mbr_id interest_y_n |
*----------------------*
| 1 n |
| 2 y |
*----------------------*
我希望识别从我的商店购买了一系列产品的会员并保存他们的详细信息以供进一步分析。
我有兴趣确定购买苹果的会员 AND 他们是否 以前 购买过梨或橙子或葡萄或甜瓜。
我的交易数据如下:
根据以上数据,会员 1 购买了苹果 (4/4/2020),但在此之前没有购买一种或多种主要产品(梨或橙子或葡萄或甜瓜)。 然而,会员2也买了苹果,但在此之前他们也买了梨(02/22/2020),因此他们是感兴趣的会员。
理想情况下,如果条件匹配,输出将只是 MBR_ID 的一列和标题为 interest_y_n 的列,如果条件不匹配,则输出为 no。
对于如何解决此问题的任何指导,我将不胜感激。
如果有帮助,我正在使用 Netezza 作为数据库平台。
嗯。 . .这听起来像是聚合:
select mbr_id,
(case when sum(case when product = 'apples' then purchase_date end) >
sum(case when product in ('pears', 'oranges', 'grapes', 'melon') then purchase_date end)
then 1 else 0
end) as is_member_of_interest
from transactions t
group by mbr_id;
case
中的条件聚合将 "apple" 购买的最早日期与其他水果的较早日期进行比较。仅当苹果在其他苹果之后购买时,该值才为真。
您也可以使用 CTE。这是 demo.
with maxDate as
(select
mbr_id,
max(purchase_date) as mxDate
from test
where product = 'apples'
group by
mbr_id
),
minDate as
(
select
mbr_id,
min(purchase_date) as mnDate
from test
group by
mbr_id
),
inter_y as
(
select
t.mbr_id,
'y' as interest_y_n
from test t
join maxDate mx
on t.mbr_id = mx.mbr_id
join minDate mn
on t.mbr_id = mn.mbr_id
where purchase_date between mnDate and mxDate
and product in ('pears', 'oranges', 'grapes', 'melon')
)
select
distinct mbr_id,
'n' as interest_y_n
from test t
where not exists (select mbr_id from inter_y iy where t.mbr_id = iy.mbr_id)
union all
select *
from inter_y
输出:
*----------------------*
| mbr_id interest_y_n |
*----------------------*
| 1 n |
| 2 y |
*----------------------*