首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择已从某个渠道购买的客户ID

选择已从某个渠道购买的客户ID
EN

Stack Overflow用户
提问于 2019-01-25 22:43:18
回答 3查看 184关注 0票数 1

我试图从网上购买的客户I列表,以及那些在网上和店内购买的客户的名单(没有客户仅限于店内)。我现在有一张桌子,看起来是这样的:

代码语言:javascript
复制
-------------------------------------------------------
**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和他们购买的渠道返回。

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-01-25 23:20:11

如果您有一个单独的客户列表,您可能需要使用exists

例如,要让在这两个地方购买过的客户:

代码语言:javascript
复制
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'
             ) ;

与聚合相比,这可能有一些优势:

  • existsnot exists可以直接使用(customer_id, store)上的索引。
  • 你可以让那些在任何渠道购买的顾客。
  • 如果需要的话,您可以获得关于客户的其他信息。
票数 0
EN

Stack Overflow用户

发布于 2019-01-25 23:07:51

只是一个小小的选择

示例

代码语言:javascript
复制
Select customerid 
      ,Channel  = min(Channel)
 From  YourTable
 Group By customerid
 Having min(Channel)=max(channel)
    and min(Channel)='online'

注意:如果您删除and min(Channel)='online',您将看到只通过一个渠道购买的客户。

返回

代码语言:javascript
复制
customerid  Channel
3           online
票数 0
EN

Stack Overflow用户

发布于 2019-01-25 23:23:54

'online'的情况下,只有客户使用not exists排除那些在'store'购买的用户。

代码语言:javascript
复制
select distinct customerid 
from tablename t
where not exists (
  select 1 from tablename where customerid = t.customerid and channel = 'store'
)

对于'online''store'的情况

代码语言:javascript
复制
select distinct customerid 
from tablename t
where 
  (select count(distinct channel) from tablename where customerid = t.customerid) = 2

您可以将上述查询组合到以下内容:

代码语言:javascript
复制
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

演示

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54373769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档