title: How to create a MySQL stored aggregate function?
body: <p>I need to write a stored function that does an aggregate operation on a column. Let's say a median (but actually, there are many different summary functions I want to implement). Ideally, I would like to have something like <code>medBy( col1 col2 col3 )</code> which then for each row returns a median of the col1 values of all the rows that have the same col2 and col3 value as this one. That way, I wouldn't have to do <code>GROUP BY</code> on the whole query, just have a repeating value in that one column.</p>
  
  <p>This question ( <a href="https://stackoverflow.com/questions/7658937/how-to-write-the-quantile-aggregate-function">How to write the quantile aggregate function?</a> ) asked something similar, but it got answered with a query rather than a stored function. </p>
  
  <p>What I would like to know is what the syntax is for specifying that the stored function should operate on the whole column <code>col1</code> and the current row's values of <code>col2</code> and <code>col3</code>.</p>
  
  <hr>
  
  <p>@djacobson: all the examples for stored functions I see treat each parameter as a single, scalar value. Maybe the question I should be starting with is how to declare an aggregate stored function at all. So, let's say I just want a function that looks like this: <code>medBy(col1)</code> and that returns the median of the column specified in the argument. Once for each row. So if I do <code>SELECT col1 my_values, medBy(col1) my_median FROM foo</code> I will get a column of values (<code>my_values</code>) and a column that is just the repeating median of the first column (<code>my_median</code>). </p>
  
  <p>Thanks.</p>