我试图搜索表并在其中一列中找到重复的任何实例,我还想返回另一列不会重复的值。
例如我的表格看起来像
ctrl_nbr curr_code
001 999
002 888
003 777
004 999
我似乎无法让我的代码同时返回ctrl_nbr和curr_code值。
这是我到目前为止所拥有的: -
select curr_code from ctrl_hdr
where nbr_sfx = 'A'
group by curr_code
having count(ctrl_nbr) > '1'
这正确地给了我有重复ctrl_nbr的curr_codes,但如果我将ctrl_nbr添加到select和group函数中,则不会返回任何内容。
我也尝试过: -
SELECT ctrl_nbr,
curr_code
FROM ctrl_hdr
WHERE curr_code IN
(SELECT curr_code
FROM ctrl_hdr
WHERE nbr_sfx = 'A'
GROUP BY curr_code
HAVING count(ctrl_nbr) > '1')
但这似乎只是进入某种循环并且不会结束。
答案 0 :(得分:1)
SELECT ctrl_nbr,
curr_code
FROM ctrl_hdr
WHERE curr_code IN
(SELECT curr_code
FROM ctrl_hdr
WHERE nbr_sfx = 'A'
GROUP BY curr_code HAVING count(ctrl_nbr) > 1)
答案 1 :(得分:1)
我可以想到三种情况。
首先,您要查找重复记录并在一行中显示:
SELECT c1.ctrl_nbr, c2.ctrl_nbr, c1.curr_code
FROM
ctrl_hdr c1 INNER JOIN
ctrl_hdr c2 ON c1.ctrl_nbr < c2.ctrl_nbr AND c1.curr_code = c2.curr_code
其次,您要选择最后/第一个副本:
SELECT c.ctrl_nbr, c.curr_code
FROM ctrl_hdr c
WHERE EXISTS ( -- it is a duplicate
SELECT * FROM ctrl_hdr
WHERE c.curr_code = curr_code AND c.ctrl_nbr != c2.ctrl_nbr)
AND NOT EXISTS ( -- it is the last dupicate
SELECT * FROM ctrl_hdr
WHERE c.curr_code = curr_code AND c.ctrl_nbr < ctrl_nbr)
最后,除了第一个/最后一个,你想得到所有重复的记录:
SELECT c.ctrl_nbr, c.curr_code
FROM ctrl_hdr c
WHERE EXISTS ( -- it is non-last duplicate
SELECT * FROM ctrl_hdr
WHERE c.curr_code = curr_code AND c.ctrl_nbr < ctrl_nbr)