【问题标题】:Teradata: Keep a random single row per column valueTeradata:每列值保持随机单行
【发布时间】:2014-04-20 00:45:14
【问题描述】:

假设我有一个包含以下行的两列表 (t1):

id   animal
---- ------
1    dog
1    pig
1    donkey
2    cow
2    horse
2    dog
2    donkey

现在,我只想为给定的 ID 保留一行。我可以做一个最小值或最大值以及一个分组:

create table t2 as (
    select id, min(animal)
    from t1
    group by id
) with data unique primary index(id);

有没有办法为每个 id 获取随机行?比最小值或最大值更难以预测的东西。

【问题讨论】:

    标签: sql teradata


    【解决方案1】:
    select id, animal
    from t1
    qualify row_number() over (partition by id order by 1) = 1
    

    这不是真正的随机,要获得真正随机的结果,您需要:

    select id, animal
       ,rnd -- without rnd the optimizer removes the Derived Table and throws an error:
            -- [5521] The RANDOM function can not be used in Aggregates or Ordered Analytical Functions.
    from 
     ( select id, animal,
          random(1,100) as rnd
       from t1
      ) as dt
    qualify row_number() over (partition by id order by rnd) = 1
    

    【讨论】:

    • 感谢您的回复。第一个查询有效。但是,第二个查询不起作用。首先,我认为有一个错字 - 它应该是“rnd”而不是“end”。其次,我收到以下错误:错误:失败 5521:RANDOM 函数不能在聚合或有序分析函数中使用。关于声明 1。
    • 是的,“结束”是一个自动更正 :-) 该错误消息很奇怪,我使用派生表来避免它,但优化器似乎“过度”优化,即删除派生表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多