如何从表中选择重复项

时间:2018-07-04 16:58:54

标签: sql sql-server

考虑一个名为“ Customer”的超大表的示例:

CustomerID   | LastName | FirstName | Address | City |
-------------|----------|-----------|---------|------|
1520         | Guere    |Francisco  |XPTO     |London|**
2214         | Santos   |António    |TUDO     |Porto |
3998         | Freixe   |Luís       |IUPO     |Quebec|
1520         | Guere    |Francisco  |XPTO     |Rome  |**
5691         | Anton    |Ana        |TIDI     |Lisbon|
1520         | Guere    |Francisco  |XPTO     |Rome  |**

从这个小例子中可以看出,对于同一位客户(CustomerID = 1520),“城市”列中的值是不同的。

例如,在这种情况下,所需的输出将是:

 CustomerID | City |
 -----------|------|
 1520       |London|
 1520       |Rome  |

我试图开发一个查询,该查询返回在City列中具有不同值的CustomerID。

SELECT CustomerID, City 
FROM (SELECT CustomerID, COUNT(DISTINCT City) FROM Customer GROUP BY CustomerID) 
WHERE City > 1

有人可以帮助我解决我开发的查询的问题吗?

3 个答案:

答案 0 :(得分:2)

如果需要城市,可以使用exists

select c.*
from customers c
where exists (select 1
              from customers c2
              where c2.customerid = c.customerid and c2.city <> c.city
             );

或者,如果您只想要客户,则可以使用group by

select customerid
from customers
group by customerid
having min(city) <> max(city);

答案 1 :(得分:1)

您可以使用HAVING进行过滤:

SELECT *
FROM Customer
WHERE CustomerID IN(SELECT CustomerID
                    FROM Customer 
                    GROUP BY CustomerID
                    HAVING COUNT(DISTINCT City) > 1);

答案 2 :(得分:1)

您可以使用以下内容:

SELECT CustomerID, City
FROM Customer
WHERE CustomerID IN (
  SELECT CustomerID
  FROM Customer
  GROUP BY CustomerID
  HAVING COUNT(DISTINCT City) > 1
)
GROUP BY CustomerID, City;

结果:

| CustomerID | City   |
|------------|--------|
| 1520       | London |
| 1520       | Rome   |