sql - 如何使用 SQL 从列中获取 >= 25%、50%、75% 的值
问题描述
我的表有一个名为Speed
(integer) 的列,我需要在该列表中选择大于 25%、50%、... 值的值。
样本数据:
+-------+
| Speed |
+-------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+-------+
期望的输出:
+--------+
| OUTPUT |
+--------+
| 3 |
| 5 |
| 8 |
+--------+
解释:
- 3 >= 25% 的数字在列表中
- 列表中 5 >= 50% 的数字
- 8 >= 75% 的数字在列表中
我认为我应该对数据进行排序,并执行以下操作:
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
,然后再使用它,那就太好了。
太感谢了。
解决方案
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
推荐阅读
- docker - 创建kafka主题时如何修复语法错误?
- laravel - 在 Silvanite/novatoolpermissions 中我应该在哪里翻译以获得许可
- mysql - MySQL 优化器没有足够快地使用 ORDER BY
- micronaut - 本机映像构建失败并出现错误:找不到主入口点类“io.micronaut.function.aws.runtime.MicronautLambdaRuntime”
- java - 使用带有 AspectJ + SpringBoot 的 @After(@annotation) 切入点的异常
- node.js - 如何用express导出不同的功能
- batch-file - telnet 上的变量
- xcode - Xcode 11 Beta 5 - 加载插件失败
- javascript - 为什么 Elm 0.19 中的“remainderBy 0 100”返回 NaN,而不是 Maybe Int?
- android - Android 应用可以在没有 ACCESS_COARSE_LOCATION 权限的情况下使用蓝牙