I am using MySQL, and My SQL table looks like this:
sales_year (INT), sales_month (INT), sales_day (INT), price (float), customer_type (TEXT)
I'd like to know which sql_query
would aggregate price data by quarter (compute the median price for each quarter, and how many observations where used to compute the median), and grouped by customer type.
I am struggling with two major steps: Median does not seem to be supported by mySQL, and also how to aggregate data by quarter - seems grouping by customer type it's very easy once those two are solved.
STRUGGLE - Computing the median....
I for example just tried creating a quarter column and it works but it computes the AVG instead of the median:
select avg(price) as avg_price, floor(sales_month/3.0+1) as
sales_quarter, count(*) as n_transactions, sales_year, customer_type
from mydb.mytable
group by sales_quarter, sales_year, customer_type;
This command works perfectly fine. But ideally I could change avg by MEDIAN but mySQL does not have such support, any suggestions on how to change this code to make it work for median purposes?
Note: I also tried installing my own median function from user defined functions in this site but the C code did not compile on my mac os X.
So the output would look like this:
sales_quarter (INT)
sales_year (INT)
median_price (FLOAT)
number_users_used_to_compute_median (INT)
customer_type (TEXT)