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 medBy( col1 col2 col3 )
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 GROUP BY
on the whole query, just have a repeating value in that one column.
This question ( How to write the quantile aggregate function? ) asked something similar, but it got answered with a query rather than a stored function.
What I would like to know is what the syntax is for specifying that the stored function should operate on the whole column col1
and the current row's values of col2
and col3
.
@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: medBy(col1)
and that returns the median of the column specified in the argument. Once for each row. So if I do SELECT col1 my_values, medBy(col1) my_median FROM foo
I will get a column of values (my_values
) and a column that is just the repeating median of the first column (my_median
).
Thanks.
Looks like you have to write a native shared library in C or C++ to pull this off. Take a look at http://dev.mysql.com/doc/refman/5.6/en/create-function-udf.html
来源:https://stackoverflow.com/questions/8947232/how-to-create-a-mysql-stored-aggregate-function