Teradata:每列保持随机单行值

时间:2014-04-15 17:08:30

标签: sql teradata

假设我有一个包含以下行的双列表(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获取一个随机行?比最小或最大值更难预测的东西。

1 个答案:

答案 0 :(得分: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