我有一个员工的记录但是我的查询返回了这个员工的2条记录,因为地址栏的不同之处是2.如何才能解决这个问题?这是可以做到的吗? EMP_ID,CUS_LAST_NAME,CUS_FIRST_NAME和GUARDIAN_ADDRESS来自3个单独的表格。
示例:
ID EMP_ID CUS_LAST_NAME CUS_FIRST_NAME GUARDIAN_ADDRESS
00000000 11111111 Jackson Michael 1111 Street Apt 1
ID EMP_ID CUS_LAST_NAME CUS_FIRST_NAME GUARDIAN_ADDRESS
00000000 11111111 Jackson Michael 1111 Street
答案 0 :(得分:0)
使用max()
快速而肮脏的方式:
select id, emp_id, emp_last_name, emp_first_name, max(address) as address
from employees
group by id, emp_id, emp_last_name, emp_first_name
替代方案:top with ties
select top 1 with ties
id, emp_id, emp_last_name, emp_first_name, address
from employees
order by row_number() over (partition by emp_id order by address desc)
两者的rextester演示:http://rextester.com/EGGA75008
答案 1 :(得分:0)
如果你不能删除其中一个 如果你选择返回哪个地址无关紧要,你可以使用聚合函数只获得一行
select ID , EMP_ID , EMP_LAST_NAME, EMP_FIRST_NAME, min(ADDRESS)
from my_table
group by ID , EMP_ID , EMP_LAST_NAME, EMP_FIRST_NAME
答案 2 :(得分:0)
如果要检测哪些员工有重复条目。
SELECT *
FROM employees
WHERE EMP_ID IN (
SELECT EMP_ID
FROM employees
GROUP BY EMP_ID
HAVING COUNT(*) > 1
)
答案 3 :(得分:0)
--start with unique list of clients
SELECT DISTINCT a.ID, a.EMP_ID, e.EMP_LAST_NAME, e.EMP_FIRST_NAME, e.ADDRESS
FROM TABLE1 a
--attach on employee data on id
OUTER APPLY (SELECT TOP 1 b.EMP_LAST_NAME, b.EMP_FIRST_NAME, b.ADDRESS
FROM TABLE2 b
WHERE a.id = b.id
--use order by clause to change order and choose what top employee record u want to choose
ORDER BY b.address
) e