【问题标题】:Automating Repeated Unions自动化重复并集
【发布时间】:2019-10-04 00:56:14
【问题描述】:

我正在运行这样的查询:

SELECT id FROM table
WHERE table.type IN (1, 2, 3)
LIMIT 15

这将返回随机抽样。我可能有来自class_1 的 7 个项目和来自class_2 的 3 个项目。我想从每个类中准确返回 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)

如果我想从 10 个类中随机抽样,而不是只从 3 个类中随机抽样,这将变得笨拙。做这个的最好方式是什么?

(我正在使用 Presto/Hive,因此对于这些引擎的任何提示将不胜感激)。

【问题讨论】:

  • 使用LIMIT 而不使用ORDER BY 意义不大。
  • @TheImpaler 你说得对,这只是随机抽样。试图使它尽可能简单的例子

标签: sql hive presto


【解决方案1】:

使用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 

【讨论】:

    【解决方案2】:

    我强烈建议添加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
    

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多