@SQL专家
我正在尝试从SQL表格中提取重复的记录,其中第一列和第二列的值相同,但第三列的值应不同。
下面是我的桌子
ID NAME DEPT
--------------------
1 VRK CSE
1 VRK ECE
2 AME MEC
3 BMS CVL
从上表中,我试图获取前两行,下面是查询,建议我为什么不能给出正确的结果。
SELECT A.ID, A.NAME, A.DEPT
FROM TBL A
INNER JOIN TBL B ON A.ID = B.ID
AND A.NAME = B.NAME
AND A.DEPT <> B.DEPT
以某种方式我没有得到预期的结果。
答案 0 :(得分:1)
您的样本数据并不能完全清楚您想要的内容。假设您要定位具有重复的第一/第二列且所有第三列值都唯一的记录组,那么我们可以尝试:
SELECT ID, NAME, DEPT
FROM
(
SELECT ID, NAME, DEPT,
COUNT(*) OVER (PARTITION BY ID, NAME) cnt,
MIN(DEPT) OVER (PARTITION BY ID, NAME) min_dept,
MAX(DEPT) OVER (PARTITION BY ID, NAME) max_dept
FROM yourTable
) t
WHERE cnt > 1 AND min_dept = max_dept;
答案 1 :(得分:0)
select *
from
(
select *,
COUNT(*) over (partition by id, [name]) cnt1,
COUNT(*) over (partition by id, [name], dept) cnt2
from dbo.T
) x
where x.cnt1 > 1 and x.cnt2 < x.cnt1;
答案 2 :(得分:0)
用于查找重复的列
select x.id, x.name, count(*)
from
(select distinct a.id, a.name, a.dept
from tab a) x
group by x.id, x.name
having count(*) > 1
答案 3 :(得分:0)
如果您想要原始行,我就去exists
:
select t.*
from tbl t
where exists (select 1
from tbl t
where t2.id = t.id and t2.name = t.name and
t2.dept <> t.dept
);
如果您只想要id
/ name
对:
select t.id, t.name
from tbl t
group by t.id, t.name
having min(t.dept) <> max(t.dept);