Found it! This is the sample dataType of Request Priority Submit_time Close_time Num days worked--------------- -------- ------------------- ------------------- ---------------KCR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2KCR Request 1 2006-01-03 13:08:10 2006-01-08 10:10:03 5KCR Request 1 2006-01-03 14:08:10 2006-01-06 13:22:06 3KCR Request 1 2006-02-03 12:08:10 2006-02-09 10:16:03 6KCR Request 1 2006-02-08 12:08:10 2006-02-14 10:16:03 6KCR Request 2 2006-01-05 13:08:11 2006-01-08 10:10:03 5KCR Request 2 2006-01-07 14:08:13 2006-01-06 13:22:06 3KCR Request 2 2006-02-03 12:08:15 2006-02-09 10:16:03 6KCR Request 3 2006-01-03 13:08:10 2006-01-08 10:10:03 5KCR Request 3 2006-01-03 14:08:10 2006-01-06 13:22:06 3KCR Request 3 2006-02-03 12:08:10 2006-02-09 10:16:03 6KCR Request 3 2006-02-08 12:08:10 2006-02-14 10:16:03 6MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2MPR Request 1 2006-10-03 13:08:10 2006-12-04 10:10:03 2
And this is the function codeCREATE FUNCTION dbo.fnMedian( @TypeOfRequest VARCHAR(20), @Priority INT, @InputStyle TINYINT)RETURNS FLOATASBEGIN DECLARE @Items INT, @Low INT, @High INT DECLARE @Values TABLE (ID INT IDENTITY(0, 1) PRIMARY KEY CLUSTERED, Value INT) IF @InputStyle = 0 OR @InputStyle IS NULL -- Ordinary MEDIAN over TypeOfRequest and Priority INSERT @Values ( Value ) SELECT Num_of_days_worked FROM MyTable WHERE [Type of Request] = @TypeOfRequest AND Priority = @Priority ORDER BY Num_of_days_worked IF @InputStyle = 1 -- Distinct MEDIAN over TypeOfRequest and Priority INSERT @Values ( Value ) SELECT DISTINCT Num_of_days_worked FROM MyTable WHERE [Type of Request] = @TypeOfRequest AND Priority = @Priority ORDER BY Num_of_days_worked IF @InputStyle = 2 -- Ordinary MEDIAN over Priority only INSERT @Values ( Value ) SELECT Num_of_days_worked FROM MyTable WHERE Priority = @Priority ORDER BY Num_of_days_worked IF @InputStyle = 3 -- Distinct MEDIAN over Priority only INSERT @Values ( Value ) SELECT DISTINCT Num_of_days_worked FROM MyTable WHERE Priority = @Priority ORDER BY Num_of_days_worked SELECT @Items = @@ROWCOUNT IF @Items % 2 = 0 -- Even number of values SELECT @High = @Items / 2, @Low = @High - 1 ELSE -- Odd number of values SELECT @High = @Items / 2, @Low = @High RETURN 1.0 * (SELECT AVG(Value) FROM @Values WHERE ID IN (@Low, @High))END
Peter LarssonHelsingborg, Sweden