They say at Christmas it is better to give than to receive.
So I will give you back your sample data in a manner that is consumable and thereby the helpers on this forum can give you better help.
WITH SampleData (Userid, [DateTime], [Check-In-Type]) AS
SELECT '001',CAST('2013-01-01 12:30' AS DATETIME),'I'
UNION ALL SELECT '001','2013-01-01 12:31','I'
UNION ALL SELECT '001','2013-01-01 12:35','I'
UNION ALL SELECT '002','2013-01-01 12:30','I'
UNION ALL SELECT '002','2013-01-01 12:31','I'
UNION ALL SELECT '002','2013-01-01 12:35','I'
UNION ALL SELECT '002','2013-01-01 12:31','O'
UNION ALL SELECT '002','2013-01-01 12:35','O'
,DateOfCheckInOut=DATEADD(day, DATEDIFF(day, 0, [DateTime]), 0)
,MinCheckIn=MIN(CASE [Check-In-Type] WHEN 'I' THEN [DateTime] END)
,MaxCheckOut=MAX(CASE [Check-In-Type] WHEN 'O' THEN [DateTime] END)
GROUP BY DATEADD(day, DATEDIFF(day, 0, [DateTime]), 0), Userid;
I've also proposed a solution that may be close to what you're looking for. As Chris said though, you need to be more clear on your business rules before we can be sure of what you're trying to do.
In particular, I was quite unsure of the data types of your columns, so I converted the Date/Time to a single column of DATETIME data type. If yours are truly separate, you can combine them and use what I gave you. Better if your table already has them combined. Keeping them separate will just cause you no end to headaches later on.
My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!
My thought question: Have you ever been told that your query runs too fast?
My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!
My temporal SQL musings: Calendar Tables
, an Easter SQL
, Time Slots
and Self-maintaining, Contiguous Effective Dates in Temporal Tables