• Stefan_G (8/1/2013)


    The original query can be formulated a little bit more elegantly as this:

    ;WITH t(i,n,c) AS

    ( SELECT i,

    ROW_NUMBER() OVER (ORDER BY i),

    COUNT(*) OVER (PARTITION BY (SELECT NULL))

    FROM #T)

    SELECT

    AVG(i) AS Median

    FROM t

    WHERE 2*n-c BETWEEN 0 AND 2;

    This version should be slightly faster because of the simpler expression in the WHERE clause

    /SG

    Awesome! I enjoy math; so proving this to myself was a lot of fun. Thanks for the new trick!