我很少使用SQL而且我遇到了这项任务的麻烦。 该表包含了我需要的所有信息。
一个人可以请求访问建筑物的某个部门,因此可能需要两种类型的认可。
我必须发现有关用户为其有权访问的每个建筑物所做的第一个请求的数据
如果用户Jon请求访问扇区“A”,2周后访问扇区“B”,我只需要返回有关 谁批准了部门的“A”和何时。
我可以找出首先请求的扇区和日期。但我不知道如何归还批准者,因为他们在另一个批准者 行。我认为这里的关键是使用票号。
记录
ID EVENTDATE TICKET USER ACTION EVENT APPROVER BUILDING SECTOR STATUS
15 7/1/2015 12:25 17C9F862 4003321 New access request Started - OHIO IT_2 Running
14 7/1/2015 12:41 17C9F862 4003321 Approved Manager approval 4001719 OHIO IT_2 Running
12 7/1/2015 15:29 17C9F862 4003321 - Finished - OHIO IT_2 Finished: Approved
13 7/1/2015 15:29 17C9F862 4003321 Approved Director Approval 4003468 OHIO IT_2 Running
10 7/1/2015 20:57 897B9A0A 4003321 New access request Started - OHIO DEVELOPMENT Running
11 7/1/2015 20:57 F3DCFB96 4003321 New access request Started - OHIO INFRA_2 Running
9 7/1/2015 20:58 897B9A0A 4003321 Approved Manager approval 4001719 OHIO DEVELOPMENT Running
8 7/1/2015 20:58 F3DCFB96 4003321 Approved Manager approval 4001719 OHIO INFRA_2 Running
7 7/1/2015 21:01 F3DCFB96 4003321 Approved Director Approval 4001547 OHIO INFRA_2 Running
6 7/1/2015 21:01 F3DCFB96 4003321 - Finished - OHIO INFRA_2 Finished: Approved
4 7/1/2015 21:03 897B9A0A 4003321 - Finished - OHIO DEVELOPMENT Finished: Approved
5 7/1/2015 21:03 897B9A0A 4003321 Approved Director Approval 4001549 OHIO DEVELOPMENT Running
3 7/1/2015 21:22 3E18483E 4003321 Approval not needed Finished - OHIO IT_1 Finished: Approved
2 7/2/2015 9:48 F902EB9C 4003321 Approval not needed Finished - UTAH FINANCE Finished: Approved
1 7/2/2015 11:08 C186101C 4003321 Approval not needed Finished - OHIO INFRA_1 Finished: Approved
期望的结果:
USER Manager Approver Director Approver BUILDING SECTOR DATE
4003321 4001719 4003468 OHIO IT_2 7/1/2015 15:29
4003321 - - UTAH FINANCE 7/2/2015 9:48
使用SQL
SELECT SEL.USER
, SEL.BUILDING
, SEL.SECTOR
, SEL.EVENTDATE
, SEL.TICKET
FROM ACCESSREQUESTS SEL
INNER JOIN
(
SELECT USER
, BUILDING
, SECTOR
, MIN(EVENTDATE) as data
FROM ACCESSREQUESTS
WHERE EVENT = 'Finished'
AND STATUS = 'Finished: Approved'
AND USER != 'null'
GROUP BY USER
, BUILDING
, SECTOR
ORDER BY USER
) RE ON RE.DATA = SEL.EVENTDATE
AND SEL.STATUS = 'Finished: Approved'
答案 0 :(得分:1)
抱歉,我无法从您的示例数据中确切地告诉我们哪一列的数据已经结束,而下一个列已经开始,所以我可能会有一些列错误,但请尝试添加:
left join (select
ticket
, approver
from accessrequests
where event = 'Approved Director Approval') as Director_Approval
on Director_Approval.ticket = sel.ticket
left join (select
ticket
, approver
from accessrequests
where event = 'Approved Manager Approval') as Manager_Approval
on Manager_Approval.ticket = sel.ticket
然后在你的选择中添加只需添加
isnull(Manager_approval.approver,'') as Manager_approver,
isnull(Director_approval.approver,'') as director_approver
你可能需要将它添加到你的子查询中,但是这应该指向正确的方向:)