如何做一个涉及日期的复杂where子句

时间:2017-06-14 18:38:48

标签: sql sql-server

我的表格如下:

Customer     Enrolled
Emp1         01/01/2014
Emp1         02/01/2014
Emp1         03/01/2014
Emp1         04/01/2014
Emp1         05/01/2014
.
.
.
Emp1         12/01/2014
Emp2         12/01/2015

我必须确定一名员工是否已注册一整年 - 即在2014年1月1日至2014年1月12日的所有行中都有。

我已经考虑过使用案例陈述,但我不确定最佳方法是什么。

这是我目前的查询:

select distinct EMPLOYEE from TABLE
WHERE ENROLLED = '2014-01-01' AND ENROLLED = '2014-02-01' AND ENROLLED = '2014-03-01' 
AND ENROLLED = '2014-04-01' AND ENROLLED = '2014-05-01' AND ENROLLED = '2014-06-01' 
AND ENROLLED = '2014-07-01' AND ENROLLED = '2014-08-01' AND ENROLLED = '2014-09-01' 
AND ENROLLED = '2014-10-01' AND ENROLLED = '2014-11-01' AND ENROLLED = '2014-12-01'

也许我只是错误地看待错误或使其复杂化。

2 个答案:

答案 0 :(得分:4)

您可以将此作为一般查询,为每位客户和每个年度提供结果:

select customer, year(enrolled)
from table
group by customer, year(enrolled)
having count(distinct(enrolled))=12

如果您只对特定年份或特定客户感兴趣,可以添加where条件,例如where year(enrolled)=1024 and customer='emp1'

答案 1 :(得分:2)

试试这个 - 这将计算多少个月。

select count(Distinct(Enrolled)) from [TABLE] where Enrolled between '1-1-2014' and '12-1-2014' and Customer='Emp1'