Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 401765
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T17:03:50+00:00 2026-05-12T17:03:50+00:00

According to MSDN , Median is not available as an aggregate function in Transact-SQL.

  • 0

According to MSDN, Median is not available as an aggregate function in Transact-SQL. However, I would like to find out whether it is possible to create this functionality (using the Create Aggregate function, user defined function, or some other method).

What would be the best way (if possible) to do this – allow for the calculation of a median value (assuming a numeric data type) in an aggregate query?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T17:03:50+00:00Added an answer on May 12, 2026 at 5:03 pm

    2019 UPDATE: In the 10 years since I wrote this answer, more solutions have been uncovered that may yield better results. Also, SQL Server releases since then (especially SQL 2012) have introduced new T-SQL features that can be used to calculate medians. SQL Server releases have also improved its query optimizer which may affect perf of various median solutions. Net-net, my original 2009 post is still OK but there may be better solutions on for modern SQL Server apps. Take a look at this article from 2012 which is a great resource: https://sqlperformance.com/2012/08/t-sql-queries/median

    This article found the following pattern to be much, much faster than all other alternatives, at least on the simple schema they tested. This solution was 373x faster (!!!) than the slowest (PERCENTILE_CONT) solution tested. Note that this trick requires two separate queries which may not be practical in all cases. It also requires SQL 2012 or later.

    DECLARE @c BIGINT = (SELECT COUNT(*) FROM dbo.EvenRows);
    
    SELECT AVG(1.0 * val)
    FROM (
        SELECT val FROM dbo.EvenRows
         ORDER BY val
         OFFSET (@c - 1) / 2 ROWS
         FETCH NEXT 1 + (1 - @c % 2) ROWS ONLY
    ) AS x;
    

    Of course, just because one test on one schema in 2012 yielded great results, your mileage may vary, especially if you’re on SQL Server 2014 or later. If perf is important for your median calculation, I’d strongly suggest trying and perf-testing several of the options recommended in that article to make sure that you’ve found the best one for your schema.

    I’d also be especially careful using the (new in SQL Server 2012) function PERCENTILE_CONT that’s recommended in one of the other answers to this question, because the article linked above found this built-in function to be 373x slower than the fastest solution. It’s possible that this disparity has been improved in the 7 years since, but personally I wouldn’t use this function on a large table until I verified its performance vs. other solutions.

    ORIGINAL 2009 POST IS BELOW:

    There are lots of ways to do this, with dramatically varying performance. Here’s one particularly well-optimized solution, from Medians, ROW_NUMBERs, and performance. This is a particularly optimal solution when it comes to actual I/Os generated during execution – it looks more costly than other solutions, but it is actually much faster.

    That page also contains a discussion of other solutions and performance testing details. Note the use of a unique column as a disambiguator in case there are multiple rows with the same value of the median column.

    As with all database performance scenarios, always try to test a solution out with real data on real hardware – you never know when a change to SQL Server’s optimizer or a peculiarity in your environment will make a normally-speedy solution slower.

    SELECT
       CustomerId,
       AVG(TotalDue)
    FROM
    (
       SELECT
          CustomerId,
          TotalDue,
          -- SalesOrderId in the ORDER BY is a disambiguator to break ties
          ROW_NUMBER() OVER (
             PARTITION BY CustomerId
             ORDER BY TotalDue ASC, SalesOrderId ASC) AS RowAsc,
          ROW_NUMBER() OVER (
             PARTITION BY CustomerId
             ORDER BY TotalDue DESC, SalesOrderId DESC) AS RowDesc
       FROM Sales.SalesOrderHeader SOH
    ) x
    WHERE
       RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)
    GROUP BY CustomerId
    ORDER BY CustomerId;
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 207k
  • Answers 207k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You could use a foreach inside another foreach: foreach ($array… May 12, 2026 at 9:18 pm
  • Editorial Team
    Editorial Team added an answer I don't know about a video inside a UIView, but… May 12, 2026 at 9:18 pm
  • Editorial Team
    Editorial Team added an answer Here's a link to a Perlmonks page which says "Beware… May 12, 2026 at 9:18 pm

Related Questions

According to MSDN form.RightToLeftLayout = True; form.RightToLeft = ifWeWantRTL() ? RightToLeft.True : RightToLeft.False; is
According to MSDN The return value specifies the result of the message processing; it
According to [MSDN: Array usage guidelines]( http://msdn.microsoft.com/en-us/library/k2604h5s(VS.71).aspx) : Array Valued Properties You should use
According to MSDN : If you did not use the Start method to start
According to MSDN SQL BOL (Books Online) page on Deterministic and Nondeterministic Functions ,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.