Skip to main content

Categories: Window

NTILE

Returns the bucket number (starting from 1) for the current row after dividing the partition into the specified number of buckets. If rows cannot be evenly divided, earlier buckets get one extra row. Requires an ORDER BY clause in the OVER window specification.

Syntax​

NTILE(buckets) OVER (PARTITION BY partition_expression ORDER BY order_expression) → bigint​

  • buckets: The number of buckets to divide the partition into. Must be a positive integer literal.
  • partition_expression (optional): An expression that groups rows into partitions.
  • order_expression: An expression that specifies the order of the rows within each partition.

Examples

NTILE example
SELECT "Category", 
"Descript",
"DayOfWeek",
NTILE(1)
OVER (
PARTITION BY "Category"
ORDER BY "DayOfWeek")
FROM Samples."samples.dremio.com"."SF_incidents2016.json"
-- Category, Descript, DayOfWeek, EXPR$3
-- ARSON, ARSON, Friday, 1
-- EMBEZZLEMENT, EMBEZZLED VEHICLE, Friday, 1
Divide rows into two buckets
SELECT val,
NTILE(2)
OVER (
ORDER BY val)
FROM (VALUES (10), (20), (30), (40)) AS t(val)
-- val, EXPR$1
-- 10, 1
-- 20, 1
-- 30, 2
-- 40, 2
Divide rows into three buckets with an uneven split
SELECT val,
NTILE(3)
OVER (
ORDER BY val)
FROM (VALUES (10), (20), (30), (40)) AS t(val)
-- val, EXPR$1
-- 10, 1
-- 20, 1
-- 30, 2
-- 40, 3
Divide rows with a NULL value into buckets
SELECT name,
NTILE(2)
OVER (
ORDER BY name)
FROM (VALUES ('Dremio'), (NULL), ('Cloud'), ('Lake')) AS t(name)
-- name, EXPR$1
-- Cloud, 1
-- Dremio, 1
-- Lake, 2
-- null, 2