简体   繁体   English

基于另一列的最大日期的列的结果

[英]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).在员工表中,有状态为“活动”的 ID,需要根据另一个表的状态 (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)但问题是这些员工中的一些在 OE 表上有多个状态,所以max(oe.text_1)最终只返回最大值 (R>T),而它应该是 T,因为它有max(text_1_eff_date)

How should I write my query to return the latest oe.text_1 status for each employee?我应该如何编写查询以返回每个员工的最新oe.text_1状态? I'm using SQL Server 2012我正在使用 SQL Server 2012

You can use row_number() :您可以使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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