我试图从网上购买的客户I列表,以及那些在网上和店内购买的客户的名单(没有客户仅限于店内)。我现在有一张桌子,看起来是这样的:
-------------------------------------------------------
**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在这种情况下,对于那些已经在网上和商店购买过的人,我是customerid 1。对于仅在线的客户列表,我想要customerid 3。我到底该如何编写代码呢?我仍然在学习SQL,所以我对SQL中正确的语法和能力不太了解。
我只想要一个客户I和他们购买的渠道返回。
谢谢!
发布于 2019-01-25 23:20:11
如果您有一个单独的客户列表,您可能需要使用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)上的索引。发布于 2019-01-25 23:07:51
只是一个小小的选择
示例
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发布于 2019-01-25 23:23:54
在'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见演示
https://stackoverflow.com/questions/54373769
复制相似问题