我正在尝试提取仅在线购买 的客户ID列表,以及另一在线和实体店购买 的客户ID列表(无客户)仅适用于店内)。我目前有一个看起来像这样的表:
-------------------------------------------------------
**customerid** **shipped_dt** **channel**
1 2018-10-31 online
1 2018-11-01 store
2 2018-11-01 store
3 2018-11-01 online
3 2018-11-02 online
在这种情况下,对于那些既在线购买又在商店购买的商品,我是customerid1。对于仅在线购物的顾客,我想要customerid 3。代码吗?我仍在学习SQL,因此对SQL中的正确语法和功能不太了解。
我只希望退回customerid和他们通过其购买的渠道。
谢谢!
答案 0 :(得分:0)
只是次要选择
示例
Select customerid
,Channel = min(Channel)
From YourTable
Group By customerid
Having min(Channel)=max(channel)
and min(Channel)='online'
注意:如果您删除and min(Channel)='online'
,则会看到仅通过一个渠道购买的客户
返回
customerid Channel
3 online
答案 1 :(得分:0)
如果您有单独的客户列表,则可能要使用exists
:
例如,要获得在两个地方都购物的客户:
select c.*
from customers c
where exists (select 1 from t where t.customer_id = c.customer_id and t.channel = 'online'
) and
exists (select 1 from t where t.customer_id = c.customer_id and t.channel = 'store'
) ;
与聚合相比,它可以具有一些优势:
exists
和not exists
可以直接使用(customer_id, store)
上的索引。答案 2 :(得分:0)
对于'online'
,只有客户使用not exists
来排除在'store'
购物的人:
select distinct customerid
from tablename t
where not exists (
select 1 from tablename where customerid = t.customerid and channel = 'store'
)
对于'online'
和'store'
:
select distinct customerid
from tablename t
where
(select count(distinct channel) from tablename where customerid = t.customerid) = 2
您可以将以上查询合并到其中:
select distinct customerid, 'online' channel
from tablename t
where not exists (
select 1 from tablename where customerid = t.customerid and channel = 'store'
)
union all
select distinct customerid, 'both' channel
from tablename t
where
(select count(distinct channel) from tablename where customerid = t.customerid) = 2
请参见demo