SQL PERCENTILE_DISC

The discrete percentile — always returns an actual value that exists in the data, never an interpolation.

What & Why

PERCENTILE_DISC selects the first observed value whose cumulative position reaches the requested percentile. It is appropriate when the result must be a value that actually appears in the data rather than an interpolated value.

See How It Works

BUSINESS QUESTION

Marketing wants each channel's observed median and 90th-percentile campaign spend.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT
  channel,
  PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY spend) AS median_spend,
  PERCENTILE_DISC(0.9) WITHIN GROUP (ORDER BY spend) AS p90_spend
FROM marketing.campaigns
GROUP BY channel
ORDER BY channel;
RESULT — observed campaign percentiles
channelmedian_spendp90_spend
email45000.0045000.00
google_ads55000.0060000.00
linkedin50000.0050000.00

Discrete percentiles always return a spend value that exists in the channel.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario