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

Count(Distinct)

Assume that the data distribution in a table is as follows.

ds (Partition)

cnt (Number of Records)

20220416

73025514

20220415

2292806

20220417

2319160

Data skew may occur when the following statements are used:

SELECT
    ds,
    COUNT(DISTINCT shop_id) AS cnt
FROM
    demo_data0
GROUP BY
    ds;

The following table lists the solutions.

No.

Solution

Description

Solution 1

General two-phase aggregation

Concatenate a random number to the partition field value.

Solution 2

Similar two-phase aggregation

Use Group By to group the ds and shop_id fields and then use Count(Distinct).

Solution 1: general two-phase aggregation

If the data of the shop_id field is evenly distributed, you can group data by the ds and shop_id fields and then perform Count(Distinct) on the ds field. If the data of the shop_id field is unevenly distributed (there are hotspot values), simple two-phase aggregation will still cause skew. In this case, you need to concatenate a random number to the partition field value using either of the following two methods to disperse the hotspot values.

-- Method 1: Concatenate a random number: CONCAT(ROUND(rand(),1)*10,'_', ds) AS rand_ds
SELECT  split_part(rand_ds, '_', 2) AS ds
       ,COUNT(*) AS id_cnt
FROM (
    SELECT  rand_ds, shop_id
    FROM    demo_data0
    GROUP BY rand_ds, shop_id
)
GROUP BY split_part(rand_ds, '_', 2);

-- Method 2: Add a random number field: round(rand()*10) AS randint10
SELECT  ds
       ,COUNT(*) AS id_cnt
FROM (
    SELECT  ds, randint10, shop_id
    FROM    demo_data0
    GROUP BY ds, randint10, shop_id
)
GROUP BY ds;

Solution 2: similar two-phase aggregation

If the data of the GroupBy and Distinct fields is evenly distributed, you can use Group By to group the ds and shop_id fields and then use the Count(Distinct) command.

SELECT  ds
       ,COUNT(*) AS cnt
FROM (
    SELECT  ds, shop_id
    FROM    demo_data0
    GROUP BY ds, shop_id
)
GROUP BY ds;