首页 > 解决方案 > 如何使用 SQL 从列中获取 >= 25%、50%、75% 的值

问题描述

我的表有一个名为Speed(integer) 的列,我需要在该列表中选择大于 25%、50%、... 值的值。

样本数据:

+-------+
| Speed |
+-------+
|     1 |
|     2 |
|     3 |
|     4 |
|     5 |
|     6 |
|     7 |
|     8 |
|     9 |
|    10 |
+-------+

期望的输出:

+--------+
| OUTPUT |
+--------+
|      3 |
|      5 |
|      8 |
+--------+

解释:

我认为我应该对数据进行排序,并执行以下操作:

SELECT speed 
FROM my_table
WHERE speed IN (ROUND(0.25 * <total_row>), ROUND(0.50 * <total_row>),..) 

但我不知道如何获得该<total_row>参考。如果我可以SELECT COUNT(speed) AS total_row,然后再使用它,那就太好了。

太感谢了。

标签: sqlselectwhere-clauseclickhouse

解决方案


create table Speed Engine=Memory 
as select number+1 X from numbers(10);

SELECT quantilesExact(0.25, 0.5, 0.75)(X)
FROM Speed

┌─quantilesExact(0.25, 0.5, 0.75)(X)─┐
│ [3,6,8]                            │
└────────────────────────────────────┘


SELECT arrayJoin(quantilesExact(0.25, 0.5, 0.75)(X)) AS q
FROM Speed

┌─q─┐
│ 3 │
│ 6 │
│ 8 │
└───┘

SELECT arrayJoin(quantilesExact(0.25, 0.499999999999, 0.75)(X)) AS q
FROM Speed

┌─q─┐
│ 3 │
│ 5 │
│ 8 │
└───┘

在 CH 领域 Join 不适用,因为它通常有数十亿行。

create table Speed Engine=MergeTree order by X  as select number X from numbers(1000000000);

SELECT quantilesExact(0.25, 0.5, 0.75)(X)
FROM Speed

┌─quantilesExact(0.25, 0.5, 0.75)(X)─┐
│ [250000000,500000000,750000000]    │
└────────────────────────────────────┘

1 rows in set. Elapsed: 7.974 sec. Processed 1.00 billion rows,

SELECT quantiles(0.25, 0.5, 0.75)(X)
FROM Speed

┌─quantiles(0.25, 0.5, 0.75)(X)────────┐
│ [244782599,500713390.5,751014086.75] │
└──────────────────────────────────────┘

1 rows in set. Elapsed: 1.274 sec. Processed 1.00 billion rows

推荐阅读