用部门名称和他们的成绩显示每个部门的重复成绩

Show duplicate grades of each department with department name and their grades

我可以显示有多少重复分数存在,但我不能显示在哪个部门。

select distinct *
  , ROW_NUMBER() over (partition by f.depname order by f.stgrade) as ranked
from (
  SELECT COUNT(*) as repeatetive, DepName, stgrade
  FROM TBL_DEPARTMANTS
  CROSS JOIN TBL_GRADES
  group by stgrade, DepName
  having count(*) > 1
) as f

您的子查询返回部门和年级计数,其中至少存在 2 行。现在,当您在非重复列表中添加 COUNT 时,您只能从子查询输出中获取 Department 和 Grade 的非重复值,考虑到 COUNT 中的差异,这将带来一些重复数据。如果你想获得不同的部门和等级列表,你可以试试下面的脚本-

SELECT DISTINCT
       DepName, 
       stgrade
FROM TBL_DEPARTMANTS
     CROSS JOIN TBL_GRADES
GROUP BY DepName,stgrade             
HAVING COUNT(*) > 1

这可能会有所帮助....

DECLARE @Table TABLE(Id INT IDENTITY(1,1), Department NVARCHAR(10), Score INT)
INSERT INTO @Table VALUES 
('A', 10),
('A', 10),
('A', 20),
('A', 40),
('B', 10),
('B', 20),
('B', 20),
('C', 20)

;WITH DupLicateData
AS
(
  SELECT Id, Department,Score, COUNT(1) OVER(PARTITION BY Department,Score ORDER BY Department,Score ASC) Rnk
  FROM @Table
)
SELECT Id, Department,Score
FROM DupLicateData
WHERE Rnk > 1
  • 不要使用 CROSS JOIN,它会产生多行 return。
  • 不需要子查询,直接在主查询中使用window解析函数。
  • 删除 row_number() over (..) 表达式中的 partition by f.depname 部分。

因此,以下查询非常适合您的需要:

select DepName, stgrade,
       row_number() over (order by g.stgrade,d.DepName) as ranked
  from TBL_DEPARTMANTS d
  left join TBL_GRADES g
    on g.DeptId = d.Id
 group by stgrade, DepName
having count(*) > 1;

假设 TBL_GRADES table 有一个名为 DeptId( 的列,否则您将需要再添加一个 table 到此查询中JOIN 语句 )

Demo