Select rows where a multiple values in one column map to the same value in another

时间:2018-12-19 11:29:48

标签: sql subquery

I have a table with the user ID, address and postcode. There can be multiple entries for each user ID (it stores all their previous addresses and post codes) but there has been an issue where addresses have been updated but the postcodes have not. I need to find all user IDs where, for a given user, an address has changed but the postcode was not updated.

+----+---------+----------+
| ID | Address | Postcode |
+----+---------+----------+
|  1 | Town A  | abcde2   |
|  1 | Town B  | abcde2   |
|  3 | Town B  | defgh6   |
|  3 | Town B  | defgh6   |
|  4 | Town C  | ijklm7   |
|  5 | Town A  | ijklm7   |
|  5 | Town C  | abcde2   |
+----+---------+----------+

The output should be:

+----+---------+----------+
| ID | Address | Postcode |
+----+---------+----------+
|  1 | Town A  | abcde2   |
|  1 | Town B  | abcde2   |
+----+---------+----------+

or simply just the IDs.

2 个答案:

答案 0 :(得分:0)

I think the below code would solve your issue:

SELECT A.ID, A.ADDRESS, A.POSTCODE FROM 
TABLE A
JOIN TABLE B ON A.ID=B.ID AND A.ADDRESS=B.ADDRESS AND A.POSTCODE<>B.POSTCODE;

答案 1 :(得分:0)

您正在寻找具有相同idpostcode但具有不同address的记录。

您可以使用简单的JOIN来实现这一点,该ON子句中定义了以上条件。

SELECT 
    t1.id, 
    t1.address,
    t1.postcode
FROM 
    table t1
    INNER JOIN table t2 
        ON  t2.id       = t1.id
        AND t2.postcode = t1.postcode
        AND t1.address  <> t2.address 
;

请注意,您的预期数据似乎存在问题:根据您提供的规范,ID 5 ...的记录将不会显示...