Search code examples
sqlt-sqlsql-server-2000

SQL duration between two dates in different rows


I would really appreciate some assistance if somebody could help me construct a MSSQL Server 2000 query that would return the duration between a customer's A entry and their B entry.

Not all customers are expected to have a B record and so no results would be returned.

Customers Audit

+---+---------------+---+----------------------+
| 1 | Peter Griffin | A | 2013-01-01  15:00:00 |
| 2 | Martin Biggs  | A | 2013-01-02  15:00:00 |
| 3 | Peter Griffin | C | 2013-01-05  09:00:00 |
| 4 | Super Mario   | A | 2013-01-01  15:00:00 |
| 5 | Martin Biggs  | B | 2013-01-03  18:00:00 |
+---+---------------+---+----------------------+

I'm hoping for results similar to:

+--------------+----------------+
| Martin Biggs | 1 day, 3 hours |
+--------------+----------------+

Solution

  • Something like the below (don't know your schema, so you'll need to change names of objects) should suffice.

    SELECT ABS(DATEDIFF(HOUR, CA.TheDate, CB.TheDate)) AS HoursBetween
    FROM dbo.Customers CA
    INNER JOIN dbo.Customers CB
    ON CB.Name = CA.Name
    AND CB.Code = 'B'
    WHERE CA.Code = 'A'