Calculate 90th continuous percentile of each region | SQL
DROP TABLE IF EXISTS Sales
CREATE TABLE Sales (
Region VARCHAR(50),
Revenue DECIMAL(10, 2)
);
INSERT INTO Sales ( Region, Revenue) VALUES
( 'North', 1000.00),
( 'North', 800.00),
( 'North', 1200.00),
( 'South', 1500.00),
( 'South', 2000.00),
( 'South', 1700.00),
( 'East', 1100.00),
( 'East', 900.00),
( 'East', 1300.00),
( 'East', 1150.00),
( 'West', 1400.00),
( 'West', 1600.00),
( 'West', 1350.00),
( 'West', 1500.00)
;
--Number of rows (n) = 4
--Desired percentile (P) = 0.9
--Position in the ordered set (k) = (n - 1) * P + 1 = (4 - 1) * 0.9 + 1 = 3.7
--The position k falls between the 3rd and 4th values (1150 and 1300).
--Using linear interpolation:
--Percentile Value = prerow+(k-mod(k))*(currentrow-prerow)
--Percentile Value = 1150+(3.7−3)×(1300−1150)
--Percentile Value=1255
Comments
Post a Comment