选择具有相同attribute1和不同attribute2的行

时间:2015-09-09 06:59:46

标签: sql ms-access

我有一张桌子

+----+------+---------+
| ID | CODE | COUNTRY |
+----+------+---------+
|  1 |   05 | France  |
|  2 |   05 | France  |
|  3 |   06 | Germany |
|  4 |   07 | France  |
|  5 |   07 | Italy   |
+----+------+---------+

我需要选择代码相同但国家不同的行。 所以结果应该是:

+------+---------+
| CODE | COUNTRY |
+------+---------+
|   07 | France  |
|   07 | Italy   |
+------+---------+

我试过

SELECT t1.code AS code, t1.country AS country
FROM countries AS t1, countries AS t2
WHERE t1.code = t2.code
AND t1.country <> t2.country;

它适用于上面示例中的表。 但如果表格如下:

+----+------+---------+
| ID | CODE | COUNTRY |
+----+------+---------+
|  1 |   05 | France  |
|  2 |   05 | France  |
|  3 |   06 | Germany |
|  4 |   07 | France  |
|  5 |   07 | Italy   |
|  6 |   07 | Italy   |
+----+------+---------+

结果是:

+------+---------+
| CODE | COUNTRY |
+------+---------+
|   07 | Italy   |
|   07 | Italy   |
|   07 | France  |
|   07 | France  |
+------+---------+

但应与上述相同。

(我使用MS Access,因此查询应该适用于Access)

1 个答案:

答案 0 :(得分:0)

您可以使用MINMAX来查看国家/地区不同的代码,然后使用它来选择所有行:

SELECT * FROM countries WHERE Code IN (
  SELECT Code
  FROM countries
  GROUP BY Code
  HAVING MIN(Country) < MAX(Country)
)