计算Oracle中的特定重复项

时间:2018-08-15 10:43:07

标签: sql oracle

您好,我无法计算分配给其他员工的电话号码(PhoneNum)的员工人数(EmpID)。但仅适用于特定组织(OrgID)

我的Oracle表如下:

TABLE OrgEmployees (OrgID, EmpID, ...)
TABLE PhoneNums (ID, EmpID, PhoneNum, ...)

特定组织的样本数据:

SELECT pn.EmpID, pn.PhoneNum FROM PhoneNums pn
WHERE EmpID IN (SELECT DISTINCT EmpID FROM OrgEmployees oe
                WHERE oe.OrgID = 'XY');

EmpID   PhoneNum
723     963264
731     963264
973     963276
729     963276
103     963450
725     963450
722     963460
731     963460
722     963462
731     963462
427     995487
295     995487
771     123151
503     123151
721     963265
104     963266

上述数据集的正确结果应该为 14

我的尝试是这样的:

SELECT pn.PhoneNum, count(pn.EmpID) FROM PhoneNums pn
WHERE pn.EmpID IN (SELECT oe.EmpID FROM OrgEmployees oe
                   WHERE oe.OrgID = 'XY') 
GROUP BY pn.PhoneNum
HAVING count (*) > 1
ORDER BY pn.PhoneNum;

但是我该如何考虑EmpID是否相同?

提前谢谢

1 个答案:

答案 0 :(得分:1)

我认为您想要count(distinct)

SELECT pn.PhoneNum, COUNT(DISTINCT pn.EmpID)
FROM PhoneNums pn
WHERE pn.EmpID IN (SELECT oe.EmpID
                   FROM OrgEmployees oe
                   WHERE oe.OrgID = 'XY'
                  ) 
GROUP BY pn.PhoneNum
HAVING COUNT(DISTINCT pn.EmpID) > 1
ORDER BY pn.PhoneNum;

我更倾向于使用JOIN而不是IN来写这个:

SELECT pn.PhoneNum, COUNT(DISTINCT pn.EmpID)
FROM PhoneNums pn JOIN
     OrgEmployees oe
     ON oe.OrgID = 'XY' AND pn.EmpID = oe.EmpID
GROUP BY pn.PhoneNum
HAVING COUNT(DISTINCT pn.EmpID) > 1
ORDER BY pn.PhoneNum;