• I believe that 10AM until the end of the day should be 840 minutes and not 839. If that is the case, I propose this easy-on-the-eyes solution:

    DECLARE @T TABLE (PatientID INT, StartDate DATETIME, EndDate DATETIME)

    INSERT INTO @T

    SELECT 1, '2012-10-15 10:00:00', '2012-10-17 08:59:00'

    UNION ALL SELECT 2, '2012-10-11 08:00:00', '2012-10-16 12:59:00'

    ;WITH Tally(n) AS (

    SELECT TOP (SELECT 1+MAX(DATEDIFF(dd, StartDate, EndDate)) FROM @T)

    ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1

    FROM sys.all_columns a CROSS JOIN sys.all_columns b)

    SELECT PatientID, StartDate, EndDate, CAST(Date AS DATE)

    ,Minutes=CASE WHEN DATEADD(dd, 0, DATEDIFF(dd, 0, StartDate)) = Date

    THEN DATEDIFF(minute, StartDate, Date+1)

    WHEN DATEADD(dd, 0, DATEDIFF(dd, 0, EndDate)) = Date

    THEN DATEDIFF(minute, Date, EndDate)

    ELSE 1440 END

    FROM @T

    CROSS APPLY (

    SELECT DATEADD(dd, n, DATEADD(dd, 0, DATEDIFF(dd, 0, StartDate)))

    FROM Tally

    WHERE n BETWEEN 0 AND DATEDIFF(dd, StartDate, EndDate)) b (Date)

    ORDER BY PatientID, Date


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    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?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St