Function to Calculate Median in SQL Server

0 votes

According to MSDN, Transact-SQL does not support Median as an aggregate function. However, I'd like to know if it's feasible to develop this capability (using the Create Aggregate function, user defined function, or some other method).

What would be the best approach to accomplish this—to permit the computation of a median value in an aggregate query, assuming a numeric data type—if it were possible?

Sep 18, 2022 in Database by Kithuzzz
• 38,010 points
1,025 views

1 answer to this question.

0 votes

Use a simple-ish median calculation for a single column in a table:

SELECT
(
 (SELECT MAX(Score) FROM
   (SELECT TOP 50 PERCENT Score FROM Posts ORDER BY Score) AS BottomHalf)
 +
 (SELECT MIN(Score) FROM
   (SELECT TOP 50 PERCENT Score FROM Posts ORDER BY Score DESC) AS TopHalf)
) / 2 AS Median
answered Sep 19, 2022 by narikkadan
• 63,620 points

Related Questions In Database

0 votes
1 answer

Convert Rows to columns using 'Pivot' in SQL Server

You can use the PIVOT function to ...READ MORE

answered Feb 8, 2022 in Database by Vaani
• 7,060 points
1,322 views
0 votes
1 answer

How to delete duplicate rows in SQL Server?

CTEs and ROW_NUMBER can be combined together which will ...READ MORE

answered Feb 10, 2022 in Database by Vaani
• 7,060 points
596 views
0 votes
1 answer

Function vs. Stored Procedure in SQL Server

Functions are calculated values that cannot make ...READ MORE

answered Feb 17, 2022 in Database by Neha
• 9,060 points

edited Feb 17, 2022 by Neha 18,441 views
0 votes
1 answer

How can we achieve excel ceiling function with significance value in SQL Server

If the underlying data types and rounding ...READ MORE

answered Apr 4, 2022 in Database by gaurav
• 23,260 points
698 views
0 votes
1 answer
0 votes
1 answer

How do I UPDATE from a SELECT in SQL Server?

MERGE INTO YourTable T USING ...READ MORE

answered Feb 3, 2022 in Database by Vaani
• 7,060 points
604 views
0 votes
0 answers

How do I UPDATE from a SELECT in SQL Server?

INSERT INTO Table (col1, col2, col3) SELECT col1, ...READ MORE

Feb 4, 2022 in Database by Vaani
• 7,060 points
331 views
0 votes
1 answer

What is a stored procedure?

A stored procedure is a set of ...READ MORE

answered Feb 4, 2022 in Database by Neha
• 9,060 points
813 views
0 votes
1 answer

How to execute function in SQL Server 2008

The function appears not to be being ...READ MORE

answered Sep 11, 2022 in Database by narikkadan
• 63,620 points
713 views
0 votes
1 answer

Calculate a Running Total in SQL Server

The problem is that the SQL Server ...READ MORE

answered Sep 11, 2022 in Database by narikkadan
• 63,620 points
1,175 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP