2016-01-22 60 views
1

我有一個客戶號碼和國家的表格。我需要將所有不同國家的客戶都歸還給他們。也就是說,不要告訴我客戶所在國家對所有記錄的價值觀是一樣的。僅當第二列不同時才返回行

在下面的例子:

╔══════════╦═════════╗ 
║ Customer ║ Country ║ 
╠══════════╬═════════╣ 
║  123 ║ USA  ║ 
║  123 ║ USA  ║ 
║  123 ║ UK  ║ 
║  456 ║ USA  ║ 
║  456 ║ USA  ║ 
║  789 ║ FRA  ║ 
║  789 ║ FRA  ║ 
║  789 ║ FRA  ║ 
╚══════════╩═════════╝ 

應該返回:

╔══════════╗ 
║ Customer ║ 
╠══════════╣ 
║  123 ║ 
╚══════════╝ 
+0

'組by'和'having'應該解決相當容易的。 –

回答

2

您可以通過COUNT(DISTINCT)group by

做到這一點
select Customer 
from (
    select 
    Customer, 
    COUNT(DISTINCT Country) cnt 
    from my_table 
    group by Customer 
) x 
where cnt > 1 

sql fiddle demo

加入having可以刪除子查詢

select 
Customer 
from my_table 
group by Customer 
having COUNT(DISTINCT Country) > 1 

sql fiddle demo

0

我認爲CTE將解決您的問題

with a(customer,country ,rank) 
as 
(
select customer,country , rank() over(partition by a order by b) as rank from table 
) 

select distinct customer from a 
where rank>1 
相關問題