sql select query和group by issue

时间:2013-07-25 07:42:19

标签: sql sql-server group-by

给出以下合同表记录

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

每位员工都可以签订多份合同

我正在尝试找到每个员工StartDate大于EndDate的无效合同。

对于给定的结果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.

有什么想法吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以尝试:

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