I'm translating a SAS project to T-SQL and there's a need to calculate the median.
There is ready to use median function in SAS (e.g.: SELECT MEDIAN(col1, col2, col3, col4) FROM myTable), but in SQL Server that doesn't exist.
I've researched and found some good examples to calculate median in T-SQL, but I don't know how to use it in my query as follows:
SELECT 
    'test' AS colTest,
    CASE 
        WHEN c1 < 0 
           THEN (10) 
           ELSE 0 
    END AS myMedian --this 10 value is just for example, it should be get from a median function
FROM 
    #tb_test
I've been trying with the example below, and got this:
CREATE TABLE #tb_test 
(
     id INT, 
     c1 INT, 
     c2 INT, 
     c3 INT, 
     c4 INT
)
INSERT INTO #tb_test VALUES(1, 2, 4, 6, 8)
INSERT INTO #tb_test VALUES(2, -1, 3, 5, 7)
SELECT * FROM #tb_test;
The table is:
|id| c1| c2| c3| c4|
+--+---+---+---+---+
|1 | 2 | 4 | 6 | 8 |
|2 |-1 | 3 | 5 | 7 |
As far as I got to calculate the median for those columns is:
--my getMedian query:
WITH cte AS
(
    SELECT 
        id, Names, Results
    FROM
        (SELECT id, c1, c2, c3, c4
         FROM #tb_test) p
    UNPIVOT
        (Results FOR Names IN (c1, c2, c3, c4)
        ) AS UNPIVOT_tb_test
)
SELECT DISTINCT PERCENTILE_CONT(0.5) 
       WITHIN GROUP (ORDER BY Results) 
       OVER (partition BY id) AS Median
FROM cte
Which results in:
|Median|
+------+
|4     |
|5     |
I've tried to include this getMedian in the final query, but no success. This desired final query would be:
SELECT 
    'test' AS colTest,
    CASE 
        WHEN c1 < 0 
           THEN ([is it possible to use the getMedian query here?]) 
        ELSE 0 
    END AS myMedian
FROM 
    #tb_test
And its respectively desired result:
|colTest | myMedian |
+--------+----------+
|test    | 4        |
|test    | 5        |
Does anyone knows how can I do it?
Thanks in advance.
 
     
     
     
    