ELSE IF @SetName = 'DY' SELECT DATEPART([year], TestDateTime) AS Year, DATEPART(DY, TestDateTime) AS DayOfYear, COUNT(TestDateTime) AS NumberOfOutages, SUM(DATEDIFF([minute], TestDateTime, next_test)) AS DownTimeInMinutes FROM (SELECT e.TestID, e.ResultID, e.TestDateTime, (SELECT MIN(d .TestDateTime) FROM Result d WHERE (d .TestID =@TestID AND d.TestDateTime >= e.TestDateTime AND datepart(DY, d.TestDateTime) =datepart(DY, e.TestDateTime) AND d .TestSimpleStatus <> e.TestSimpleStatus)) AS next_test FROM Result e WHERE (e.TestID = @TestID) AND (e.TestSimpleStatus = 'DOWN') AND (TestDatetime >= '1/1/2005')) x WHERE (DATEDIFF([minute], TestDateTime, next_test) > 0) GROUP BY DATEPART(DY, TestDateTime), DATEPART([year], TestDateTime) ORDER BY DATEPART(DY, TestDateTime) DESC, DATEPART([year], TestDateTime) DESC