Ask Your Question
3

How can the query be improved to extract multiple Nth percentiles in MySQL 5.6?

asked 2022-09-13 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-19 15:00:00 +0000

devzero gravatar image

One way to extract multiple Nth percentiles in MySQL 5.6 is to use the PERCENTILE_DISC() function in combination with a subquery that generates a list of percentile values to extract.

For example, the following query extracts the 20th, 50th, and 90th percentiles for the "salary" column in the "employees" table:

SELECT 
  PERCENTILE_DISC(0.2) WITHIN GROUP (ORDER BY salary) as p20,
  PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary) as p50,
  PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY salary) as p90
FROM 
  employees;

This query uses the PERCENTILE_DISC() function to calculate the specified percentiles (in this case, the 20th, 50th, and 90th). The WITHIN GROUP (ORDER BY) clause specifies that the percentile values should be calculated based on the ordering of the "salary" column.

To extract multiple percentiles, simply add additional PERCENTILE_DISC() expressions to the SELECT list with the desired percentile values. The subquery inside the function will generate the appropriate percentile values for each expression.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-13 11:00:00 +0000

Seen: 15 times

Last updated: Apr 19 '21