我想每个员工只返回一个角色(EmpID),这是最后一个处理特定任务的员工(FixEndDate)。下面是模型表。
DECLARE @Problem TABLE
(
ProblemID INT
, ProblemDate DATETIME
, LogBy NVARCHAR(50)
)
INSERT INTO @Problem(ProblemID,ProblemDate,LogBy)
VALUES (1,CAST('2015-01-29 10:53:46.000'AS DATETIME),'Carl')
, (2,CAST('2015-01-21 10:53:46.000'AS DATETIME),'Paul')
, (3,CAST('2015-01-21 13:53:46.000'AS DATETIME),'Paul')
, (4,CAST('2015-01-21 15:53:46.000'AS DATETIME),'Paul')
DECLARE @Fix TABLE
(
FixID INT
, ProblemID INT
, EmpID INT
, FixStartDate DATETIME
, FixEndDate DATETIME
)
INSERT INTO @Fix(ProblemID, EmpID, FixStartDate, FixEndDate)
VALUES (1, 12, CAST('2015-02-02 10:53:46.000'AS DATETIME),CAST('2015-02-02 12:50:46.000'AS DATETIME))
, (1, 14, CAST('2015-02-03 10:53:46.000'AS DATETIME),CAST('2015-02-03 12:50:46.000'AS DATETIME))
, (2, 11, CAST('2015-02-04 10:53:46.000'AS DATETIME),CAST('2015-02-04 01:55:46.000'AS DATETIME))
, (2, 12, CAST('2015-02-04 05:56:46.000'AS DATETIME),CAST('2015-02-03 08:50:46.000'AS DATETIME))
, (3, 10, CAST('2015-02-04 07:53:46.000'AS DATETIME),CAST('2015-02-04 18:10:46.000'AS DATETIME))
, (3, 15, CAST('2015-02-05 10:53:46.000'AS DATETIME),CAST('2015-02-05 12:10:46.000'AS DATETIME))
, (3, 18, CAST('2015-02-05 11:53:46.000'AS DATETIME),CAST('2015-02-05 01:10:46.000'AS DATETIME))
, (4, 20, CAST('2015-02-07 12:53:46.000'AS DATETIME),CAST('2015-02-08 03:10:46.000'AS DATETIME))
, (4, 23, CAST('2015-02-08 11:53:46.000'AS DATETIME),CAST('2015-02-09 18:10:46.000'AS DATETIME))
, (4, 13, CAST('2015-02-10 16:53:46.000'AS DATETIME),CAST('2015-02-11 16:10:46.000'AS DATETIME))
我尝试过:
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, f.FixEndDate
FROM @Problem AS p
INNER JOIN @Fix AS f
ON p.ProblemID = f.ProblemID
INNER JOIN (
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, MAX(f.FixEndDate) AS Fixed
FROM @Problem AS p
INNER JOIN @Fix AS f
ON p.ProblemID = f.ProblemID
GROUP BY f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
) AS d
ON d.EmpID = f.EmpID
AND d.Fixed = f.FixEndDate
ORDER BY FixEndDate DESC
这是前进的方向吗?
答案 0 :(得分:1)
试
SELECT f.EmpID
, p.ProblemID
, p.ProblemDate
, f.FixStartDate
, f.FixEndDate
FROM @Problem AS p
INNER JOIN (select * from (select * ,row_number() over (partition by ProblemID order by fixenddate desc) as rno from @Fix) t where rno=1) AS f
ON p.ProblemID = f.ProblemID