Here we have a table of 34 rows.
DECLARE @x TABLE (TotalStd INT) INSERT @x (TotalStd) VALUES (16), (21), (23), (25), (26), (28), (29), (29), (30), (30), (31), (32), (32), (32), (32), (33), (34), (34), (35), (35), (35), (36), (38), (40), (41), (43), (43), (44), (45), (46), (47), (48), (48), (57) SELECT '@x', TotalStd FROM @x ORDER BY TotalStd
We want to divide into quartiles. If we use NTILE , the bucket sizes will be about the same size (8 to 9 lines each), but the links will be arbitrarily broken:
SELECT '@x with NTILE', TotalStd, NTILE(4) OVER (ORDER BY TotalStd) quantile FROM @x
See how 30 appears twice: once in quantile 1 and once in quantile 2. Similarly, 43 appears in both quantiles 3 and 4.
What I have to find are 10 elements in quantile 1, 8 in quantile 2, 7 in quantile 3 and 9 in quantile 4 (i.e. not perfect separation 9-8-9-8, but such separation is impossible, if we are not allowed to break the bonds arbitrarily). I can do this with NTILE to define cutoff points in a temporary table:
DECLARE @cutoffs TABLE (quantile INT, min_value INT, max_value INT) INSERT @cutoffs (quantile, min_value) SELECT y.quantile, MIN(y.TotalStd) FROM (SELECT TotalStd, NTILE(4) OVER (ORDER BY TotalStd) AS quantile FROM @x) y GROUP BY y.quantile
We will use the boundary values ββin the @cutoffs table to create the resulting table:
SELECT x.TotalStd, c.quantile FROM @xx INNER JOIN @cutoffs c ON x.TotalStd >= c.min_value AND x.TotalStd < c.max_value