Updated on 2026-11-06 GMT+08:00

ROW_NUMBER(TopN)

The following is an example of top 10.

SELECT  main_id, type
FROM (
    SELECT  main_id
           ,type
           ,ROW_NUMBER() OVER(PARTITION BY main_id ORDER BY type DESC) AS rn
    FROM   data_demo2
) A
WHERE   A.rn <= 10;

The following table lists the solutions to data skew.

No.

Solution

Description

Solution 1

Two-phase aggregation using SQL statements

Add a random column or concatenate a random number as a parameter in the partition.

Solution 2

Two-phase aggregation using user-defined aggregate functions (UDAFs)

Achieve the minimum heap (TopN) using UDAFs.

Solution 1: two-phase aggregation using SQL statements

To ensure that data in each partition group is as evenly distributed as possible in the map phase, add a random column and use it as a parameter in the partition.

-- 1. Generate a random number based on the row distribution in the source table.
SELECT  main_id, type
FROM (
    SELECT  main_id, type
           ,ROW_NUMBER() OVER(PARTITION BY main_id ORDER BY type DESC) AS rn
    FROM (
        SELECT  main_id, type
        FROM (
            SELECT  main_id
                   ,type
                   ,ROW_NUMBER() OVER(PARTITION BY main_id, src_pt ORDER BY type DESC) AS rn
            FROM (
                SELECT  main_id, type
                       ,CAST(ceil(110 * rand()) % 11 AS INT) AS src_pt
                FROM   data_demo2
            )
        ) B
        WHERE B.rn <= 10
    )
) A
WHERE A.rn <= 10;
-- 2. Customize a random number.
SELECT  main_id, type
FROM (
    SELECT  main_id, type
           ,ROW_NUMBER() OVER(PARTITION BY main_id ORDER BY type DESC) AS rn
    FROM (
        SELECT  main_id, type
        FROM (
            SELECT  main_id, type
                   ,ROW_NUMBER() OVER(PARTITION BY main_id, src_pt ORDER BY type DESC) AS rn
            FROM (
                SELECT  main_id, type
                      , CAST(ceil(10 * rand()) AS INT) AS src_pt
                FROM   data_demo2
            )
        ) B
        WHERE B.rn <= 10
    )
) A
WHERE A.rn <= 10;

Solution 2: two-phase aggregation using UDAFs

For Spark, window functions and approx_count_distinct or collect_set are recommended. Alternatively, use groupBy().agg(collect_list()) and a UDF to obtain the top N records.

# Use Spark built-in operators, which are more authentic. (Avoid using UDAFs.)
from pyspark.sql import functions as F
from pyspark.sql.window import Window
# Step 1: Add a random column.
df1 = df.withColumn("src_pt", F.ceil(F.rand()*10))
# Step 2: Obtain the top N records from the scattered partitions.
w1 = Window.partitionBy("main_id","src_pt").orderBy(F.col("type").desc())
df2 = df1.withColumn("rn", F.row_number().over(w1)).filter("rn <= 10")
# Step 3: Obtain the top N records again after merging.
w2 = Window.partitionBy("main_id").orderBy(F.col("type").desc())
result = df2.withColumn("rn2", F.row_number().over(w2)).filter("rn2 <= 10").drop("rn","rn2","src_pt")