2016-07-25 148 views
0

HI在我的SQL行我有以下類似下面的問題 源表:如果條件不滿足替代值從那裏條件滿足

表1:

Employee Role Contract Hours IS primary Role Valid from 
1 Role A 35 Y 01/03/2015 
1 Role B 35 Y 01/06/2016 
1 Role C 0 N 01/07/2016 
2 Role A 20 Y 01/01/2016 
2 Role B 0 N 01/01/2016 
2 Role C 25 Y 01/04/2016 
3 Role A 35 Y 01/04/2016 

因此,在員工1的示例中,他於2015年3月1日開始在公司工作,2016年6月1日更換了職位,並於2017年7月1日添加了第二個休閒職位 我需要一個查詢來返回任何角色和最新主要角色與合同時間:

Employee Role Contract Hours Valid from Primary Role – Contract Hours 
1 Role A 35 01/03/2015 Role A – 35 
1 Role B 35 01/06/2016 Role B – 35 
1 Role C 0 01/07/2016 Role B – 35 
2 Role A 20 01/01/2016 Role A – 20 
2 Role B 0 01/01/2016 Role A – 20 
2 Role C 25 01/04/2016 Role C – 25 
3 Role A 35 01/04/2016 Role A – 35 

最好的結果,我有回報的附加列空值,如果主要作用是N

Select 
「Employee」, 
「Role」, 
「Contract Hours」, 
「Valid From」, 
Case 
When 「Is primary Role」 = Y 
Then 「Role」 + ‘-‘ + 「Contract Hours」 
    Else NULL 
END as 「Primary Role – Contract Hours」 

從表1

但是,而不是「其他空」,我需要找到一個在任何次要角色的有效日期之前添加最新的主要值的方法。

回答

0
/* 
DROP TABLE T; 
CREATE TABLE T (Employee int, Role varchar(10), ContractHours int, ISprimaryRole char(1), Validfrom date); 
insert into t values 
(1, 'Role A', 35 , 'Y' , '2015-03-01'), 
(1, 'Role B', 35 , 'Y' , '2016-06-01'), 
(1, 'Role C', 0 , 'N' , '2016-07-01'), 
(2, 'Role A', 20 , 'Y' , '2016-01-01'), 
(2, 'Role B', 0 , 'N' , '2016-01-01'), 
(2, 'Role C' , 25 , 'Y' , '2016-04-01'), 
(3, 'Role A' , 35 , 'Y' , '2016-04-01'); 
*/ 


select * 
from 
(
select *, 
     (Select max(t1.validfrom) from t t1 where t1.Employee = t.employee and t1.isprimaryrole = 'Y' and t1.Validfrom <= t.validfrom) maxisp 
from t 
) s 
left outer join t t1 on t1.employee = s.employee and t1.Validfrom = s.maxisp and t1.isprimaryrole = 'Y' 

結果

+----------+--------+---------------+---------------+------------+------------+----------+--------+---------------+---------------+------------+ 
| Employee | Role | ContractHours | ISprimaryRole | Validfrom | maxisp  | Employee | Role | ContractHours | ISprimaryRole | Validfrom | 
+----------+--------+---------------+---------------+------------+------------+----------+--------+---------------+---------------+------------+ 
|  1 | Role A |   35 | Y    | 2015-03-01 | 2015-03-01 |  1 | Role A |   35 | Y    | 2015-03-01 | 
|  1 | Role B |   35 | Y    | 2016-06-01 | 2016-06-01 |  1 | Role B |   35 | Y    | 2016-06-01 | 
|  1 | Role C |    0 | N    | 2016-07-01 | 2016-06-01 |  1 | Role B |   35 | Y    | 2016-06-01 | 
|  2 | Role A |   20 | Y    | 2016-01-01 | 2016-01-01 |  2 | Role A |   20 | Y    | 2016-01-01 | 
|  2 | Role B |    0 | N    | 2016-01-01 | 2016-01-01 |  2 | Role A |   20 | Y    | 2016-01-01 | 
|  2 | Role C |   25 | Y    | 2016-04-01 | 2016-04-01 |  2 | Role C |   25 | Y    | 2016-04-01 | 
|  3 | Role A |   35 | Y    | 2016-04-01 | 2016-04-01 |  3 | Role A |   35 | Y    | 2016-04-01 | 
+----------+--------+---------------+---------------+------------+------------+----------+--------+---------------+---------------+------------+