SQL Select 按列划分的随机行
SQL Select random rows partitioned by a column
我有一个这样的数据集
| Country | id |
-------------------
| a | 5 |
| a | 1 |
| a | 2 |
| b | 1 |
| b | 5 |
| b | 4 |
| b | 7 |
| c | 5 |
| c | 1 |
| c | 2 |
我需要一个查询,其中 returns 2 个随机值来自 ('a'、'c') 的国家/地区:
| Country | id |
------------------
| a | 2 | -- Two random rows from Country = 'a'
| a | 1 |
| c | 1 |
| c | 5 | --Two random rows from Country = 'c'
这应该有效:
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 服务器中使用 Postgres 或 newid()
,请将 rand()
替换为 random()
。
我有一个这样的数据集
| Country | id |
-------------------
| a | 5 |
| a | 1 |
| a | 2 |
| b | 1 |
| b | 5 |
| b | 4 |
| b | 7 |
| c | 5 |
| c | 1 |
| c | 2 |
我需要一个查询,其中 returns 2 个随机值来自 ('a'、'c') 的国家/地区:
| Country | id |
------------------
| a | 2 | -- Two random rows from Country = 'a'
| a | 1 |
| c | 1 |
| c | 5 | --Two random rows from Country = 'c'
这应该有效:
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 服务器中使用 Postgres 或 newid()
,请将 rand()
替换为 random()
。