Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 datetime intersection

Author  Topic 

laailalalaa
Yak Posting Veteran

57 Posts

Posted - 2010-04-25 : 16:43:31
i have table T(id, startdate1, enddate1, startdate2, enddate2). i need to write a select that displays:

[id, startdate, enddate], where startdate and enddate delimit the intersection between [startdate1, enddate1] and [startdate2, enddate2].

any ideas on how to proceed?

thanks

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-04-25 : 17:01:57
SELECT id, MAX(s) AS startdate, MIN(e) AS enddate
FROM
(
SELECT id, startdate1, enddate1, 1 FROM tbl
UNION ALL
SELECT id, startdate2, enddate2, 2 FROM tbl
)D(id, s, e, k)
GROUP BY id
HAVING MAX(CASE WHEN k = 1 THEN e END) > MIN(CASE WHEN k = 2 THEN s END)

EDIT: Replace MAX with MIN in HAVING clause.
NEW EDIT: MAX or MIN in this case are same.
Go to Top of Page

laailalalaa
Yak Posting Veteran

57 Posts

Posted - 2010-04-25 : 17:19:48
brilliant solution :D
thanks a lot ms65g >:D<
Go to Top of Page

ms65g
Constraint Violating Yak Guru

497 Posts

Posted - 2010-04-25 : 17:21:34
You are welcome
Go to Top of Page
   

- Advertisement -