仅当第二列不同时才返回行

时间:2016-01-22 06:21:23

标签: sql sql-server-2008

我有一张包含客户编号和国家/地区的表格。我需要退回所有具有不同国家/地区的客户。也就是说,不要向我展示客户所有记录的国家/地区价值相同的地方。

在下面的例子中:

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

应该返回:

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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