获取两个日期之间的差距小于或等于5天的记录

时间:2018-01-09 07:09:47

标签: sql-server

我有两个表:具有唯一票证ID的票证和具有多个票证记录的票证历史(如打开,出席,转发,关闭等)。想要获得的记录 当前机票开放且最后关闭机票的客户在5天内有差距。使用以下查询提供已关闭票证的多个记录。想要最后关闭的票据动作日期以计算天差距。如果当前打开的机票和最后关闭的机票在5天内有差距,则要将当前机票重复考虑。

SELECT A.ticketId,A.username,A.status,A.areaName,A.subject
,d.deptId,d.action,d.actionDate odate,g.actionDate cdate,g.status 
FROM tb_tickets A
INNER JOIN (SELECT action, actiondate, ticketId, deptId FROM tb_ticketHistory WHERE action='Open') d
on a.ticketId = d.ticketid
INNER JOIN (SELECT th.ticketid, tt.username, tt.status, actiondate FROM tb_ticketHistory th 
INNER JOIN tb_tickets tt 
on th.ticketId = tt.ticketId WHERE th.action='closed') g
on a.username = g.username
WHERE d.deptId=5 AND a.status!='closed'
ORDER BY ticketId ASC

1 个答案:

答案 0 :(得分:1)

由于您还没有提供准确的结构和样本数据,因此很难给出确切的答案。但您可以通过将其作为结构进行调整来尝试使用代码 -

select CurrentOpenTickets.customerid, CurrentOpenTickets.ticketid from
(
select customerid, t.ticketid, actiondate from [dbo].[tb_ticketHistory ] th
inner join [dbo].[tb_Tickets] t on t.ticketid = th.ticketid
where t.status != 'C'
) CurrentOpenTickets
inner join 
(select customerid, t.ticketid, actiondate from [dbo].[tb_ticketHistory ] th
inner join [dbo].[tb_Tickets] t on t.ticketid = th.ticketid
where th.status = 'C'
) PastClosedTickets

on CurrentOpenTickets.customerid = PastClosedTickets.customerid and datediff(DAY, CurrentOpenTickets.actiondate, PastClosedTickets.actiondate) <= 5