我提前道歉,这可能是一个问题和答案的基本问题,但我不知道如何通过搜索来找到正确的结果。
我有一个表(在其他列中)包含客户编号的程序名称。我需要确定只有一个特定程序而没有其他程序的客户。一个简化的例子:
Col1 = Customer_Number,Col2 = Program_Name
客户1有三条记录,因为它们已注册2013BA1111,2013BO1161和2013BO1163。客户2只有一条记录,因为它们仅在2013BA1111中注册。
使用Teradata SQL Assistant,如果我选择WHERE Program_Name ='2013BA1111',将返回客户1和客户2,因为它们都已注册到程序2013BA1111中。我只想选择客户2,因为他们只有2013BA1111。
谢谢!
答案 0 :(得分:6)
在标准(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
答案 1 :(得分:1)
也许是这样的:
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
外部查询正在选择具有给定Program_Name
的所有记录,然后它与每个具有不等于给定Program_Name
的记录的每个人的内部查询以及外部查询相结合检查以确保连接的内部查询没有匹配。
答案 2 :(得分:1)
我不熟悉&#34; Teradata&#34;,但您应该可以在sql中使用以下内容:
SELECT
Col1 AS Customer,
COUNT(*) AS TotalOccurences
FROM
YourTable
GROUP BY Col1
HAVING COUNT(*) = 1
答案 3 :(得分:0)
这将在SQL服务器中执行。不确定Teradata是否相同......
select t.Col1, min(t.Col2) from myTable t
group by t.Col1
having count(*) = 1
答案 4 :(得分:0)
您是否只需要customer_number或其他列?
SELECT Customer_Number
FROM tab
GROUP BY 1
HAVING SUM(CASE WHEN Program_Name = '2013BA1111' THEN 0 ELSE 1 END) = 1;
SELECT *
FROM tab AS t1
WHERE Program_Name = '2013BA1111'
AND NOT EXISTS
(
SELECT * FROM tab AS t2
WHERE t1.Customer_Number = t2.Customer_Number
AND Program_Name <> '2013BA1111'
);
SELECT *
FROM tab
QUALIFY
SUM(CASE WHEN Program_Name = '2013BA1111' THEN 0 ELSE 1 END)
OVER (PARTITION BY Customer_Number) = 1;