表A(调任表)
员工 调出部门 调入部门 调任日期
people officeout officein date()
a b c 2015-09-05
a c b 2015-09-25
a1 c d 2015-09-15
表B(员工档案)
员工 所属部门
people workoffice
a b
a1 c
a2 d
现要求查询在2015-09-01~2015-09-30期间员工的工作部门及工作时间段
查询结果如下:
people office begindate enddate
a b 2015-09-01 2015-09-04
a c 2015-09-05 2015-09-24
a b 2015-09-25 2015-09-30
a1 c 2015-09-01 2015-09-14
a1 d 2015-09-15 2015-09-30
a2 d 2015-09-01 2015-09-30
哪位大神给sql语句?
------解决思路----------------------
DECLARE @sdt DATE
DECLARE @edt DATE
SET @sdt = CONVERT(DATE,'2015-09-01')
SET @edt = CONVERT(DATE,'2015-09-30')
;WITH tb AS
(
SELECT
Row_Number() Over(PARTITION BY people ORDER BY dt) AS tid,
people, office, dt
FROM
(
SELECT people, officein AS office, dt
FROM tbl10
UNION ALL
SELECT people, workoffice AS office, @sdt AS dt
FROM tbl11
) AS t1
)
SELECT t1.people, t1.office, t1.dt AS bdt,
ISNULL(dateadd(DAY, -1, t2.dt), @edt) AS edt
FROM tb AS t1
LEFT JOIN tb AS t2
ON t1.tid = (t2.tid -1)