SQL:如何提取执行了操作A但从未执行过操作B的客户ID?
我需要做的是:所有只在线订购的客户(即客户1和客户3) 考虑到表格的结构(客户4在列表中出现了两次),我很难将客户4从数据提取中删除,因为他们在网上和店内购买 数据: 客户1-网上购买 客户2-在店内购买 客户3-网上购买 客户4-网上购买 客户4-在店内购买 这是我的代码,我肯定仍然会得到客户4,但不确定如何排除他们。当然,我处理的全部数据要大得多SQL:如何提取执行了操作A但从未执行过操作B的客户ID?,sql,Sql,我需要做的是:所有只在线订购的客户(即客户1和客户3) 考虑到表格的结构(客户4在列表中出现了两次),我很难将客户4从数据提取中删除,因为他们在网上和店内购买 数据: 客户1-网上购买 客户2-在店内购买 客户3-网上购买 客户4-网上购买 客户4-在店内购买 这是我的代码,我肯定仍然会得到客户4,但不确定如何排除他们。当然,我处理的全部数据要大得多 SELECT DISTINCT(table.customer_id) FROM table WHERE ((table.purchase_chan
SELECT DISTINCT(table.customer_id)
FROM table
WHERE ((table.purchase_channel='store')
AND NOT (table.purchase_channel='online'))
我将使用条件聚合:
select t.customer_id
from t
group by t.customer_id
having sum(case when t.purchase_channel = 'store' then 1 else 0 end) > 0 and
sum(case when t.purchase_channel = 'online' then 1 else 0 end) = 0;
我发现这种结构在各种条件下都非常方便。根据您的具体情况,您可以将其缩短为:
select t.customer_id
from t
where t.purchase_channel in ('store', 'online')
group by t.customer_id
having min(t.purchase_channel) = 'store' ;
不使用
select customer_id from table t
where t.customer_id not in
(
SELECT table.customer_id
FROM table
WHERE
table.purchase_channel='online'
) and t.purchase_channel='store'
使用“不存在”:
您应该尝试这里建议的所有变体。对于小桌子来说,这无关紧要,但对于大桌子来说,这会有很大的不同。例如,在Sql Server中,我发现“不存在”通常生成最佳查询计划。确保您在(客户id、采购渠道)上有索引。
在大型分布式系统中,“不在”可能工作得更好。
DISTINCT
不是一个函数,它是SELECT DISTINCT
的一部分,在整个选定行上工作。删除那些多余的括号以使事情更清楚,即只需执行选择不同的表。客户id…
。谢谢!我一直很想看看我如何清理代码。这对我所需要的非常有效。我真的很感激!!
SELECT *
FROM table t
WHERE not exists(
select 1 from table
where customer_id = t.customer_id
and purchase_channel='online')