2016-07-20 84 views
0

我想在月初檢查部門中有多少員工。按日期查詢記錄,但如果最新不合適,則排除記錄

我想我需要選擇開始一個月的記錄或更早版本,不包括那些在最新記錄的類型爲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年5月1日應該是

4 2015.04.17 Gamma IT Hiring 
5 2016.04.23 Delta IT Hiring 
6 2016.05.01 Epsilon IT Hiring 

因爲阿爾法已經終止

回答

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' 
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 
+0

1.在SQL Server,你不能引用列別名where子句。 2.使用內部連接可以有效地排除未被解僱的員工 - 您想要使用左連接(但是,當期限日期爲空時,您必須添加其他檢查)。使用子查詢根本不需要 - 您可以將表連接在一起。 3.「id」不是加入表格的適當關鍵,「employeename」可能是。它可能看起來像這樣:https://data.stackexchange.com/stackoverflow/query/514762 – jpw

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