简体   繁体   中英

SQL - using datediff between two tables with join

I have a scenario where I need to generate a report addressing the following requirement:

Display status of each support ticket. For each ticket include number of updates, the problem, status, time elapsed between ticket being logged and first update, and the time between ticket being logged and final update.

The database schema for relevant tables is:

Ticket (TicketID, Problem, Status, Priority, LoggedTime, CustomerID, ProductID)
TicketUpdate (TicketUpdateID, Message, UpdateTime, TicketID)

I have the following so far:

SELECT t.TicketID,
       COUNT(tu.TicketID) AS 'Number of Updates',
       t.Problem,
       t.Status,
       (
           SELECT DATEDIFF(HOUR, MIN(UpdateTime), MAX(UpdateTime))
           FROM TicketUpdate
           WHERE TicketID = t.TicketID
       ) AS 'Hours bw Q and Last response'
FROM Ticket t
    LEFT JOIN TicketUpdate tu
        ON t.TicketID = tu.TicketID
GROUP BY t.TicketID,
         t.Problem,
         t.Status;

Which doesn't address the requirement, but I was experimenting with the function. I was expecting I would be able to use alias inside the datediff function but apparently I can't (correct me if I'm wrong please).

Any help with this issue would be greatly apreciated. Thanks!

Aggregate the updates first;

SELECT t.*, tu.NumUpdates,
       DATEDIFF(HOUR, t.LoggedTime, tu.FirstUpdateTime),
       DATEDIFF(HOUR, t.LoggedTime, tu.LastUpdateTime)
FROM Ticket t LEFT JOIN
     (SELECT tu.TicketID, COUNT(*) as NumUpdates,
             MIN(tu.UpdateTime) as firstUpdateTime,
             MAX(tu.UpdateTime) as lastUpdateTime
      FROM TicketUpdate tu
      GROUP BY tu.TicketID
     ) tu
     ON t.TicketID = tu.TicketID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM