2

我一直是这个论坛的长期读者。它对我帮助很大,但是我有一个问题,我找不到特定于我要求的解决方案。

我的任务是制定一个指标来确定“员工绩效评估”逾期的天数。数据采用以下格式:

EmployeeID LastEvalCompleteDate NextEvalDueDate
1001       2010-01-01           2010-11-01
1001       2010-11-20           2011-11-01
1001       2011-10-29           2012-11-15
1002       NULL                 2013-12-01

根据上面的示例数据,员工1001自 2010 年 1 月 1 日以来已经进行了 3 次评估。员工1002已于今年开始工作,他的第一次评估将于 2013 年 12 月 1 日到期。

我需要做的是将数据转换为这种格式:

EmployeeID EvalDueDate EvalCompleteDate DaysPastDue
1001       2010-11-01  2010-11-20       19
1001       2011-11-01  2011-10-29       -2
1001       2012-11-15  NULL             342 (based on today's date)
1002       2013-12-01  NULL             -39 (based on today's date)

正如您所注意到的,我通过获取NextEvalDueDate列的值并将其映射到EvalDueDate新表中的列来派生一个新行。我还将NEXT 行LastEvalCompleteDate的列中的值映射到该列。NextEvalDueDate

我无法遍历给定的行EmployeeID。我尝试使用ROW_NUMBER() OVER (PARTITION BY ...),但它并没有带我去任何地方。

我感谢任何形式的帮助。谢谢你。

4

2 回答 2

1

您使用ROW_NUMBER() OVER (PARTITION BY ...). 不知道你卡在哪里了,但应该是这样的:

WITH CTE AS 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY NextEvalDueDate) RN
    FROM dbo.Table1
)
SELECT 
    c1.EmployeeID
  , c1.NextEvalDueDate AS EvalDueDate
  , c2.LastEvalCompleteDate AS EvalCompleteDate 
  , DATEDIFF(DAY, c1.NextEvalDueDate, COALESCE(c2.LastEvalCompleteDate, GETDATE())) AS DaysPastDue
FROM CTE c1
LEFT JOIN CTE c2 ON c1.EmployeeID = c2.EmployeeID AND c1.RN = c2.RN - 1
ORDER BY c1.EmployeeID, c1.RN
于 2013-10-23T16:35:56.167 回答
0
DECLARE @Results TABLE
(
    EmployeeID INT NOT NULL,    
    RowNum INT NOT NULL,        
        PRIMARY KEY (RowNum, EmployeeID),
    LastEvalCompleteDate DATE,
    NextEvalDueDate DATE
);
INSERT  @Results (RowNum, EmployeeID, LastEvalCompleteDate, NextEvalDueDate)
SELECT  ROW_NUMBER() OVER(PARTITION BY e.EmployeeID ORDER BY e.LastEvalCompleteDate),
        e.EmployeeID,
        e.LastEvalCompleteDate,
        e.NextEvalDueDate
FROM    dbo.EmployeeEvaluation e;

WITH Base
AS
(
SELECT  crt.RowNum,
        crt.EmployeeID,
        crt.NextEvalDueDate AS EvalDueDate,
        nxt.LastEvalCompleteDate AS EvalCompleteDate 
FROM    @Results crt
LEFT JOIN @Results nxt ON crt.EmployeeID = nxt.EmployeeID AND crt.RowNum + 1 = nxt.RowNum
)
SELECT  r.*,
        DATEDIFF(DAY, r.EvalDueDate, ISNULL(r.EvalCompleteDate, GETDATE())) AS DaysPastDue
FROM    Base r
ORDER BY r.EmployeeID, r.RowNum
于 2013-10-23T17:40:20.737 回答