0

给定以下合同表记录

Id EmployeeId StartDate    EndDate
1  5601       2011-01-01   2011-09-01
2  5601       2011-09-02   2012-05-01
3  5601       2012-02-01   2012-08-01
4  5602       2011-01-01   2011-09-01
5  5602       2011-07-01   2012-10-01

每个员工可以有多个合同

我试图找到StartDateEndDate每个员工更大的无效合同。

对于给定的结果Id=3Id=5是无效的。我所做的是:

SELECT a.Id
FROM Contracts a
GROUP BY a.EmpId
HAVING a.StartDate > a.EndDate

但我得到这个错误:

Column 'Contract.Id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the group by clause.

任何想法 ?

4

2 回答 2

1

如果我理解正确,您想要 StartDate大于之前的EndDate 的记录?您可以使用CTEROW_NUMBER()函数来执行此操作 - 加入上一个和当前记录。

WITH CTE AS 
(
   SELECT *, ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY StartDate) RN
   FROM Contracts
)
SELECT * FROM CTE c1
INNER JOIN CTE c2 ON c1.RN + 1 = c2.RN AND c1.EmployeeID = c2.EmployeeID
WHERE c1.EndDATE > c2.StartDate
于 2013-07-25T07:50:24.110 回答
0

你可以试试:

SELECT a.Id, a.EmpId
FROM Contracts a
WHERE a.StartDate > a.EndDate
GROUP BY a.Id, a.EmpId
于 2013-07-25T07:46:43.833 回答