This article is half-done without your Comment! *** Please share your thoughts via Comment ***
Check the below input data and expected output and find the median value from the given range of Numbers.
Input Data:
1 2 3 4 5 6 7 |
Number ----------- 1 5 10 16 20 |
Expected Output:
1 2 3 |
Median ----------- 10 |
Create a sample table:
1 2 3 |
CREATE TABLE tbl_TestMedian (Number INT) INSERT INTO tbl_TestMedian VALUES (1),(5),(10),(16),(20) Go |
Solution 1:
1 2 3 4 5 6 7 8 |
SELECT ( (SELECT MAX(Number) FROM (SELECT TOP 50 PERCENT Number FROM tbl_TestMedian ORDER BY Number) AS LastSet) + (SELECT MIN(Number) FROM (SELECT TOP 50 PERCENT Number FROM tbl_TestMedian ORDER BY Number DESC) AS FirstSet) ) / 2 AS Median |
Solution 2:
1 2 3 4 5 6 7 |
SELECT MAX(Number) AS Median FROM ( SELECT Number, NTILE(4) OVER (ORDER BY Number) AS MiddleRange FROM tbl_TestMedian ) T WHERE MiddleRange = 2 |
Please try the different solution for this puzzle and share it via comment...