根据用户部门更改历史记录分配日志

时间:2017-11-17 18:45:14

标签: sql sql-server

我必须创建一个select语句,该语句根据用户打印从MS SQL Server获取信息。问题是,每个用户都有一个特定的部门ID,我们从该部门获得了不断变化的历史记录。因此,我的报告必须足够智能,以便从特定时段(例如1个月)分配打印,并且如果该用户更改了部门,则会将这些打印分配给正确的部门。 (例如,他的部门在前15天是IT,有一天它被改为开发)......

让我展示一下我的数据库:

USER

id       name              department_id

1        John Doe          2


DEPARTMENT

id          name

1           T.I

2           Dev

3           R&D

4           FRONT

5           BACK


USER_DEPARTMENT_HISTORY

id  user_id  department_id start_date   end_date

1   1        1             1900-01-01   2017-11-10

2   1        2             2017-11-10   2017-11-15 

3   1        3             2017-11-15   2999-01-01 


LOG

id          user_id     pages       printed_on

1           1           5           2017-11-10 00:00:00.000

2           1           7           2017-10-12 00:00:00.000

3           1           3           2017-10-10 00:00:00.000

4           1           3           2017-09-10 00:00:00.000

5           1           3           2017-09-11 00:00:00.000

如果我们不应该考虑改变部门历史,这将是一个很好的方法

1 个答案:

答案 0 :(得分:0)

您可以使用joins,如下所示

select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from user u
inner join USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id] 
inner join Department d on d.id = dh.department_id
inner join LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date

完整脚本:

create table #user
( id int,
[name] varchar(25),
department_id int
)

insert into #user
values(1,'John Doe',2)


create table #Department
(
id int,
name varchar(25)
)


insert into #DEPARTMENT
values(1,'T.I'),
(2,'Dev'),
(3,'R&D'),
(4,'FRONT'),
(5,'BACK')

create table #USER_DEPARTMENT_HISTORY
(
id  int ,
[user_id]   int,
department_id int,
start_date   date,
end_date date
)


insert into #USER_DEPARTMENT_HISTORY
values(1,1,1,'1900-01-01','2017-11-10'),
(2,1,2,'2017-11-10','2017-11-15'),
(3,1,3,'2017-11-15','2999-01-01')

create table #LOG
(
id  int ,
[user_id]   int,
pages int,
printed_on   datetime
)

insert into #LOG
values(1,1,5,'2017-11-10 00:00:00.000'),
(2,1,7,'2017-10-12 00:00:00.000'),
(3,1,3,'2017-10-10 00:00:00.000'),
(4,1,3,'2017-09-10 00:00:00.000'),
(5,1,3,'2017-09-11 00:00:00.000')


select  u.name as [user] ,d.name as department,l.pages,l.printed_on
from #user u
inner join #USER_DEPARTMENT_HISTORY dh on u.id = dh.[user_id] 
inner join #Department d on d.id = dh.department_id
inner join #LOG l on l.[user_id] = u.id and printed_on>=[start_date] and printed_on <end_date

drop table #user
drop table #USER_DEPARTMENT_HISTORY
drop table #Department
drop table #LOG