我想找到SHARED_NUMBER
匹配的行,
但是UNIQUE_NUMBER
不同
TABLE_ID|SHARED_NUMBER|UNIQUE_NUMBER|
-------------------------------------
1 | 999111 | B |
1 | 999111 | B |
1 | 999111 | B |
1 | 999444 | C |
1 | 999888 | D |<
1 | 999888 | D |<
1 | 999111 | B |
1 | 999444 | C |
1 | 999888 | C |<<<<<<<
1 | 999111 | B |
因此,我只想查找存在SHARED_NUMBER
重复项的行,并且如果这些重复项中的任何没有没有匹配项 UNIQUE_NUMBER
全部三个都返回-
所以我应该回来:
1 | 999888 | D |<
1 | 999888 | D |<
1 | 999888 | C |<<<<<<<
我一直试图添加到:
SELECT SHARED_NUMBER, COUNT(*) c
FROM
table GROUP BY SHARED_NUMBER HAVING c > 1
-------
WHERE
table.UNIQUE_NUMBER != c.UNIQUE_NUMBER
但这不起作用。
答案 0 :(得分:2)
使用COUNT(DISTINCT UNIQUE_NUMBER)
来查找是否存在不同的唯一编号。
SELECT SHARED_NUMBER
FROM table
GROUP BY SHARED_NUMBER
HAVING COUNT(DISTINCT UNIQUE_NUMBER) > 1
如果需要获取具有相同共享号但具有不同唯一号的所有行,请使用该子查询将原始表连接起来:
SELECT t1.*
FROM table AS t1
JOIN (
SELECT SHARED_NUMBER
FROM table
GROUP BY SHARED_NUMBER
HAVING COUNT(DISTINCT UNIQUE_NUMBER) > 1
) AS t2 ON t1.SHARED_NUMBER = t2.SHARED_NUMBER