我提前道歉,这可能是一个问题和答案的基本问题,但我不知道如何通过搜索来找到正确的结果.
我有一个表(在其他列中)包含客户编号的程序名称.我需要确定只有一个特定程序而没有其他程序的客户.一个简化的例子:
Col1 = Customer_Number,Col2 = Program_Name
客户1有三条记录,因为它们已注册2013BA1111,2013BO1161和2013BO1163.客户2只有一条记录,因为它们仅在2013BA1111中注册.
使用Teradata SQL Assistant,如果我选择WHERE Program_Name ='2013BA1111',则将返回Customer 1和Customer 2,因为它们都已注册到程序2013BA1111中.我只想选择客户2,因为他们只有2013BA1111.
谢谢!
在标准(ANSI/ISO)SQL中,派生表是您的朋友.在这里,我们将customer表与一个派生表连接起来,该表生成只有1的客户列表
select *
from customer c
join ( select customer_id
from customer
group by customer_id
having count(program_name) = 1
) t on t.customer_id = c.customer_id
where ... -- any further winnowing of the result set occurs here
Run Code Online (Sandbox Code Playgroud)
也许是这样的:
select Customer_Number, Program_Name
from YourTable t1
left join (
select Customer_Number
from YourTable t2
where t2.Program_Name <> '2013BA1111'
) t3 on t1.Customer_Number = t3.Customer_Number
where
t1.Program_Name = '2013BA1111'
and t3.Customer_Number is null
Run Code Online (Sandbox Code Playgroud)
外部查询选择具有给定 的所有记录Program_Name,然后将其与具有不等于给定记录的每个人的内部查询连接Program_Name,并且外部查询检查以确保连接的内部查询没有一场比赛。