Case closed!
Thanks Planen!
Your solution works fine!
I worked paralell with you and my solution resulted in this code:
Select ID,
category = min(category),
from_date = Min(from_date),
to_date = max(to_date)
from
(SELECT ID,
category,
from_date,
to_date,
-- I create a dummycolumn (Bryt) that gives a "group identity" for those
rows that should have a low/high-date
-- since the last "group" will have a NULL-value I use coalesce to replce
the null value with the IDs Max to_date
Bryt = coalesce((select min(from_date) from Role1 x where x.ID = a.ID
and x.from_date > a.from_date
and x.category <> a.category),
(select max(to_date) from Role1 x where x.ID = a.ID))
FROM role1 a) z
group by ID, Bryt -- I use the dummycolumn as group by
order by 1,3
// Jocke
"Plamen Ratchev" wrote:
> Here is one set based solution:
>
> SELECT id, category, from_date,
> (SELECT MIN(to_date)
> FROM Foo AS C
> WHERE NOT EXISTS
> (SELECT *
> FROM Foo AS D
> WHERE C.id = D.id
> AND C.category = D.category
> AND C.to_date >= DATEADD(DAY, -1, D.from_date)
> AND C.to_date < D.to_date)
> AND C.to_date >= A.from_date
> AND C.id = A.id
> AND C.category = A.category) AS to_date
> FROM Foo AS A
> WHERE NOT EXISTS
> (SELECT *
> FROM Foo AS B
> WHERE A.id = B.id
> AND A.category = B.category
> AND A.from_date > B.from_date
> AND A.from_date <= DATEADD(DAY, 1, B.to_date));
>
> --
> Plamen Ratchev
> http://www.SQLStudio.com
> .
> >> Stay informed about: Transact SQL teaser