简体   繁体   中英

Explanation for a mysql Query

The query below is something I found online and it seems to correctly calculate the median. However, just by looking at it, I have no idea what it is doing to find the median. Can someone who understands all the parts to this query (cast, substring index, group concat, separator etc.) please explain to me/break down how this query works?

select CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(cost_per_unit ORDER BY
cost_per_unit SEPARATOR ','),',', 50/100 * COUNT(*) ), ',', -1) AS DECIMAL) 
AS '50th Percentile' from table

Any and all help is welcome!

thanks

I'll start from inside and work my way out

GROUP_CONCAT(cost_per_unit ORDER BY cost_per_unit SEPARATOR ',')

Returns Every cost_per_unit as a string separated by a ',' and ordered by value

ie 1,2,3,4,4,5,6,7 (7 commas)

SUBSTRING_INDEX(previous_value,',', 50/100 * COUNT(*) )

Returns the string before half of the ',' ie 1,2,3,4

SUBSTRING_INDEX(previous_value,',', -1),

Returns the part after the last (first backwards) ',' ie 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM