Fix SQL Server Error: “The function ‘APPROX_PERCENTILE_CONT’ must have a WITHIN GROUP clause”

If you’re getting SQL Server error 10754 that reads “The function ‘APPROX_PERCENTILE_CONT’ must have a WITHIN GROUP clause” it’s probably because you’re calling the APPROX_PERCENTILE_CONT() function, but you’ve omitted the WITHIN GROUP clause.

To fix this issue, add a WITHIN GROUP clause to the function (and make sure it has an ORDER BY clause).

Example of Error

Here’s an example of code that produces the error:

SELECT APPROX_PERCENTILE_CONT( 0.5 ) 
FROM Products;

Result:

Msg 10754, Level 15, State 2, Server 1f674fe22ff6, Line 30
The function 'APPROX_PERCENTILE_CONT' must have a WITHIN GROUP clause.

I got the error because I omitted the WITHIN GROUP clause from the APPROX_PERCENTILE_CONT() function.

Solution

To fix the issue, all I need to do is include a valid WITHIN GROUP clause:

SELECT
    APPROX_PERCENTILE_CONT( 0.5 ) 
        WITHIN GROUP ( ORDER BY ProductPrice )
FROM Products;

Result:

20.369999999999997

This time it worked without error.

It’s worth pointing out that the WITHIN GROUP clause requires an ORDER BY clause. Also, there must be exactly one ORDER BY expression (no more, no less).