如何只为特定记录获取不同的客户?

时间:2018-02-09 09:51:24

标签: sql

前: -

     Customer_ID    Transaction_type
         111           Payroll
         111           Saving
         112           payroll
         113           Online 
         113           Payroll
         114           Payroll

1)我想要Customer_Id 112和114谁只有工资单帐户 2)我希望客户111和113分别拥有其他交易类型的工资单。

2 个答案:

答案 0 :(得分:0)

假设您要查询只有一种交易类型的客户

SELECT Customer_ID, COUNT(*)
FROM yourtable
GROUP BY Customer_ID    
HAVING COUNT(*) = 1;

明确查询具有不同交易类型的客户

的方法相同
 SELECT Customer_ID, COUNT(*)
 FROM yourtable
 GROUP BY Customer_ID    
 HAVING COUNT(*) > 1;

PS:这可以根据您的问题进行改进

答案 1 :(得分:0)

问题仍然不太清楚,但简单的GROUP BY条款足以满足上述要求

谁只有一个工资核算帐户

select Customer_ID 
from table
group by Customer_ID
having count(Transaction_type) = 1 and 
sum(case when Transaction_type = 'payroll' then 1 else 0 end) = 1    

谁有其他交易类型与工资单分开

select Customer_ID 
from table
group by Customer_ID
having count(Transaction_type) > 1 and 
sum(case when Transaction_type = 'payroll' then 1 else 0 end) = 1