Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

How to solve Median with GROUP BY?

Asked by Carolyn Buckland Jul 12, 2021 1.2K views 1 answer
Share

About this question

Suppose the following table t1:

=================

|  tag  |  val  |       --+ for the sake of simplicity, val is non NULL

=================

|   a1  |  v1   |

|   a1  |  v2   |

|   a1  |  v3   |

|   a1  |  v4   |

|   a1  |  v5   |

|   a2  |  v6   |

|   a2  |  v7   |

|   a2  |  v8   |

|   a2  |  v9   |

|   ... | ...   |

=================

If you execute the script below in MySQL: SELECT `tag`, AVG(`val`) FROM `t1` GROUP BY `tag` You would get the average values grouped by the column tag:

=================

|  tag  | AVG() |

=================

|   a1  | avg1  |

|   a2  | avg2  |

|   a3  | avg3  |

|   a4  | avg4  |

|   ... |  ...  |

=================

Besides AVG(), MySQL has several other built-in functions to calculate aggregate values (e.g. SUM(), MAX(), COUNT(), and STD()) that could be used in the same way as in the script aforementioned. However, there is no built-in function for the median.

This issue has already come up several other times at SE; however, most of them are related to tables without GROUP BY. The only one with GROUP BY seems to be MySql: Count median grouped by day; however, the script seems to be overcomplicated.

Question

What would be an easy and simple way (if possible) to calculate this median?

Follow-up

Excellent article that complements the accepted answer:

http://danielsetzermann.com/howto/how-to-calculate-the-median-per-group-with-mysql/

Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.