sql - Redshift 选择随机记录但避免重复

标签 sql amazon-web-services amazon-redshift

我在 Redshift 中有一个表,其中有样本 ID 71082 的以下记录:

id       trm_num        start_time
71082   PCMAMGA759551   2012-05-02 09:41:54
71082   PCMAMGA759551   2015-06-02 13:23:39
71082   PCMAMGA759551   2015-09-03 13:23:39
71082   PCMAMGA759551   2015-12-11 07:25:25
71082   PCMAMGA759551   2017-01-10 09:03:22

我只想为每个 ID 选择 1 个随机记录。 为此,我尝试了查询:

select * from mytable where id=71082 order by random limit 1;

它为我获取了随机记录。但该表有 1000 多个不同的 ID。我如何修改我对其他 ID 的查询?

最佳答案

使用窗口函数 ROW_NUMBER,每个 ID 随机排序:

select id, trm_num, start_time
from
(
  select
    id, trm_num, start_time,
    row_number() over (partition by id order by random()) as rn
  from mytable
) numbered
where rn = 1;

关于sql - Redshift 选择随机记录但避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49670057/

相关文章:

php - 使用 LIKE 检查多个 MySQL 列与单个值

mysql - 如何在单个查询中使用 IF() 语句获取单独的字段数据

amazon-web-services - AWS Lambda-发生故障时如何停止重试

amazon-web-services - Amplify 的 completeNewPassword 方法为用户数据抛出 TypeError

amazon-web-services - cloudfront 指向 s3 上托管的旧版 React

mysql - 将 SQLite 数据迁移到 MySQL 并管理/更新外键?

sql - 使用连接更新表,如果不存在则为 NULL

amazon-web-services - 我在 AWS 中创建安全组时出错

postgresql - Amazon redshift 中的每月保留

在复制表中的行时更新所需的 MySQL 特殊 INSERT/SELECT 语句