简体   繁体   中英

Result of a column based on the max date of another column

I am in the process of cleaning up some data. In the Employee table there are ID's who have a status of 'active' which needs to be changed based on another table's status (text_1). This is

SELECT e.BW_ID, max(oe.TEXT_1) as 'Employee Status', max(oe.text_1_eff_date) 'Effective Date'
FROM    EMPLOYEE e
INNER JOIN ORG_EMPLOYMENT oe on e.BW_ID = oe.BW_ID
WHERE e.CONTROLLED_GROUP_STATUS = 'active'
GROUP BY e.BW_ID

Which looks like this(sample data):

在此处输入图片说明

But the problem is that some of these employees have multiple status' on the OE table, so the max(oe.text_1) ends up just returning the greatest value (R>T) when it should be T because it has the max(text_1_eff_date)

How should I write my query to return the latest oe.text_1 status for each employee? I'm using SQL Server 2012

You can use row_number() :

SELECT t.*
FROM (SELECT e.BW_ID, oe.TEXT_1 AS Employee_Status, oe.text_1_eff_date AS Effective_Date,
             ROW_NUMBER() OVER (PARTITION BY e.BW_ID ORDER BY oe.text_1_eff_date) AS SEQ
      FROM EMPLOYEE e INNER JOIN 
           ORG_EMPLOYMENT oe 
           ON e.BW_ID = oe.BW_ID
      WHERE e.CONTROLLED_GROUP_STATUS = 'active'
     ) t
WHERE SEQ = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM