我想在本月初查看部门中有多少员工。
我认为我需要选择月初或更早的记录,不包括部门员工的最新记录类型为2(即终止)的记录
id date employeename department type
1 2016-03-01 Alpha IT 1
2 2016-04-12 Alpha IT 2
3 2016-04-15 Beta Operations 1
4 2015-04-17 Gamma IT 1
5 2016-04-23 Delta IT 1
6 2016-05-01 Epsilon IT 1
7 2016-05-02 Delta IT 2
8 2016-05-18 Gamma IT 2
9 2016-05-21 Beta Operations 2
10 2016-05-31 Zeta IT 1
在此示例中,对于IT部门的< = 2016.05.01的员工应
4 2015.04.17 Gamma IT Hiring
5 2016.04.23 Delta IT Hiring
6 2016.05.01 Epsilon IT Hiring
因为Alpha已被终止
答案 0 :(得分:0)
使用一对加入的子查询可以工作(它们也可以是保存的视图)。这也为您提供了雇佣和任期日期的功能支点。
select a.id, a.date as hired, b.date as term, a.empName, a.dept from
--hire date
(select id, date, empName, dept from emp where type=1) a
join
--term date
(select id, date from emp where type=2) b
on a.id = b.id
where '5-1-2016' between hired and term
答案 1 :(得分:0)
USE sandbox
GO
declare @t table (id int, dte date, employeename varchar(10), department varchar(10), type int)
insert into @t values
(1 , '2016-03-01', 'Alpha' , 'IT' , 1),
(2 , '2016-04-12', 'Alpha' , 'IT' , 2),
(3 , '2016-04-15', 'Beta' , 'Operations' , 1),
(4 , '2015-04-17', 'Gamma' , 'IT' , 1),
(5 , '2016-04-23', 'Delta' , 'IT' , 1),
(6 , '2016-05-01', 'Epsilon', 'IT' , 1),
(7 , '2016-05-02', 'Delta' , 'IT' , 2),
(8 , '2016-05-18', 'Gamma' , 'IT' , 2),
(9 , '2016-05-21', 'Beta' , 'Operations' , 2),
(10, '2016-05-31', 'Zeta' , 'IT' , 1)
select *
from @t
where employeename not in (select employeename from @t where type = 2 and dte <= '2016-05-01')
and dte <= '2016-05-01'
答案 2 :(得分:0)
;with x as (
select *, row_number() over (partition by employeename order by date desc) rn
from @tbl
where date <= '20160501'
and department = 'IT'
)
select * from x where rn = 1 and type <> 2