自动化重复联合
Automating Repeated Unions
我是运行这样的查询:
SELECT id FROM table
WHERE table.type IN (1, 2, 3)
LIMIT 15
这 return 是随机抽样。我可能有 class_1
中的 7 项和 class_2
中的 3 项。我想 return 每个 class 中的 5 个项目,并且以下代码有效:
SELECT id FROM (
SELECT id, type FROM table WHERE type = 1 LIMIT 5
UNION
SELECT id, type FROM table WHERE type = 2 LIMIT 5
UNION ...
ORDER BY type ASC)
如果我想从十个 class 中随机抽样,而不是只从三个中抽样,这会变得很笨拙。做这个的最好方式是什么?
(我使用的是 Presto/Hive,因此对于这些引擎的任何提示都将不胜感激)。
使用 row_number
之类的函数来执行此操作。这使得选择与类型数量无关。
SELECT id,type
FROM (SELECT id, type, row_number() over(partition by type order by id) as rnum --adjust the partition by and order by columns as needed
FROM table
) T
WHERE rnum <= 5
我强烈建议添加 ORDER BY
。无论如何,你可以这样做:
with
x as (
select
id,
type,
row_number() over(partition by type order by id) as rn
from table
)
select * from x where rn <= 5
我是运行这样的查询:
SELECT id FROM table
WHERE table.type IN (1, 2, 3)
LIMIT 15
这 return 是随机抽样。我可能有 class_1
中的 7 项和 class_2
中的 3 项。我想 return 每个 class 中的 5 个项目,并且以下代码有效:
SELECT id FROM (
SELECT id, type FROM table WHERE type = 1 LIMIT 5
UNION
SELECT id, type FROM table WHERE type = 2 LIMIT 5
UNION ...
ORDER BY type ASC)
如果我想从十个 class 中随机抽样,而不是只从三个中抽样,这会变得很笨拙。做这个的最好方式是什么?
(我使用的是 Presto/Hive,因此对于这些引擎的任何提示都将不胜感激)。
使用 row_number
之类的函数来执行此操作。这使得选择与类型数量无关。
SELECT id,type
FROM (SELECT id, type, row_number() over(partition by type order by id) as rnum --adjust the partition by and order by columns as needed
FROM table
) T
WHERE rnum <= 5
我强烈建议添加 ORDER BY
。无论如何,你可以这样做:
with
x as (
select
id,
type,
row_number() over(partition by type order by id) as rn
from table
)
select * from x where rn <= 5