如果我们在前三列中有重复项,则从第二个表中获取单个记录

时间:2014-12-08 15:23:53

标签: sql sql-server sql-server-2008 tsql

您能否为我提供以下方案的解决方案。

我有两张表employee_nameEmployee_details

让我们想一想,Employee_details表包含多年的数据。我想从两个表中检索数据。

表1:employee_name

emp_no  name    
1       A
2       B
3       C etc..

表2:Employee_details

emp_no col1 col2 address salary year  addr_changed_By addr_changed_on  sal_changed_by Sal_changed_on

1      x1   y1   addr1   100000 2013    P            01/12/2014      q              09/12/2014

1      x1   y1   addr2   150000 2014    P            01/12/2014      q              09/12/2014


2      x2   y2   addr4   200000 2014    m            19/12/2014      n              10/12/2014
  1. 我希望获得员工详细信息以及姓名。如果前3列 在具有相同数据的第二个表中,我们应该得到单个 记录。
  2. 此外,我需要更新记录时的数据以及数据 更新了每个员工记录?
  3. 最后,根据以上数据,我想得到两条记录,如:

    employee name: A
    address : addr1
    last updated by: q
    last updated on : 09/12/2014
    
    employee name : B
    address : addr4
    last updated by: m
    last updated on : 19/12/2014
    

2 个答案:

答案 0 :(得分:0)

我会留给你取名字 这只是薪水

select last.* 
from 
(
    select temp_no, col1, col2, address, salary, year
         , addr_changed_By, addr_changed_on, sal_changed_by, Sal_changed_on 
         , row_number() over (partition by temp_no, col1, col2 order by Sal_changed_on desc) as rownum 
      from Employee_details
) as last 
where rownum = 1

答案 1 :(得分:0)

使用CROSS APPLY

SELECT emp_no, col1, col2, Changed_On, Changed_By
FROM employee_details ed
    CROSS APPLY (SELECT TOP 1
                    CASE WHEN addr_changed_on > Sal_changed_on THEN addr_changed_on ELSE Sal_changed_on END Changed_On,
                    CASE WHEN addr_changed_on > Sal_changed_on THEN addr_changed_By ELSE sal_changed_by END Changed_By
                FROM employee_details ed2
                WHERE emp_no = ed.emp_no 
                    AND col1 = ed.col1
                    AND col2 = ed.col2
                ORDER BY Changed_On DESC) chn
GROUP BY emp_no, col1, col2, Changed_On, Changed_By

并发布BLAM的代码......

select last.* 
from 
(
    select emp_no, col1, col2, address, salary, year, Changed_By, Changed_On 
         , row_number() over (partition by emp_no, col1, col2 order by Changed_On desc) as rownum 
      from Employee_details
        CROSS APPLY (SELECT CASE WHEN addr_changed_on > Sal_changed_on THEN addr_changed_on ELSE Sal_changed_on END Changed_On,
                            CASE WHEN addr_changed_on > Sal_changed_on THEN addr_changed_By ELSE sal_changed_by END Changed_By) chn
) as last 
where rownum = 1