Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 |
+--------------+----------------+
like image 287
user1990366 Avatar asked Dec 15 '25 06:12

user1990366


1 Answers

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'
like image 158
Will A Avatar answered Dec 16 '25 20:12

Will A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!