这是我的查询,其中显示当前结果。
SELECT
Distinct CONVERT(int, Employees_1.Emp_Badge_No) AS Emp_Badge_No,
Employees_1.Emp_LastName, Employees_1.Emp_FirstName, Employees_1.Email,
Employees_1.NT_Name, Employees_1.Dept_key,
Employees_1.Emp_LastName + ',' + Employees_1.Emp_FirstName AS FullName,
dbo.department_vw.DepartmentShortName AS deptname,
Employees_1.active_flag
FROM data_common.dbo.employees_union_vw AS Employees_1
INNER JOIN dbo.department_vw
ON Employees_1.Dept_key = dbo.department_vw.DepartmentKey
示例数据:
我需要帮助才能达到预期效果。我将使用现有的sql查询修改什么? 我希望保留所有记录,即使它不是不活动的,只要不重复Emp_Badge_No。我只想删除那些重复的Emp_Badge_No。
提前致谢。
答案 0 :(得分:1)
您可能希望使用ROW_NUMBER
。根据要检索的重复条目中的哪一行修改ORDER BY
子句:
WITH Cte AS(
SELECT
e.Emp_Badge_No,
e.Emp_LastName,
e.Emp_FirstName,
e.Email,
e.NT_Name,
e.Dept_key,
e.Emp_LastName + ',' + e.Emp_FirstName AS FullName,
d.DepartmentShortName AS deptname,
e.active_flag,
rn = ROW_NUMBER() OVER(PARTITION BY e.Emp_Badge_No ORDER BY e.Active)
FROM data_common.dbo.employees_union_vw AS e
INNER JOIN dbo.department_vw d
ON e.Dept_key = d.DepartmentKey
)
SELECT
Emp_Badge_No,
Emp_LastName,
Emp_FirstName,
Email,
NT_Name,
Dept_key,
FullName,
deptname,
active_flag
FROM Cte
WHERE rn = 1
如果有重复,上面的内容将获得非活动记录。如果您想要获取活动记录,请将rn
替换为:
ROW_NUMBER() OVER(PARTITION BY Emp_Badge_No ORDER BY e.Active DESC)
如果您不关心它是活动还是非活动,请将rn
替换为:
ROW_NUMBER() OVER(PARTITION BY Emp_Badge_No ORDER BY (SELECT NULL))