【问题标题】:SQL Select random rows partitioned by a columnSQL 选择按列分区的随机行
【发布时间】:2022-01-20 17:19:00
【问题描述】:

我有一个如下所示的数据集

| Country    | id |
-------------------
| a       | 5  |
| a       | 1  |
| a       | 2  |
| b       | 1  |
| b       | 5  |
| b       | 4  |
| b       | 7  |
| c       | 5  |
| c       | 1  |
| c       | 2  |

我需要一个查询,该查询从国家在 ('a', 'c') 中返回 2 个随机值:

| Country | id |
------------------
| a       | 2 |  -- Two random rows from Country = 'a'
| a       | 1 | 
| c       | 1 |
| c       | 5 | --Two random rows from Country = 'c'

【问题讨论】:

  • 标记一个 RDBMS。对此没有标准的 SQL 解决方案。

标签: sql random


【解决方案1】:

这应该可行:

select Country, id from
(select Country, 
id,
row_number() over(partition by Country order by rand()) as rn
from table_name
) t
where Country in ('a', 'c') and rn <= 2

如果您在 SQL Server 中使用 Postgres 或 newid(),请将 rand() 替换为 random()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2017-04-09
    • 2014-03-18
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2017-08-29
    相关资源
    最近更新 更多