gpt4 book ai didi

sql - 如何在 SQL (Oracle) 中随机排列数据?

转载 作者:行者123 更新时间:2023-12-04 23:57:26 25 4
gpt4 key购买 nike

随机排列数据的最佳方法是什么?
例子:

id col1    col2     col3
1 data11 data12 data13
2 data21 data22 data23
3 data31 data32 data33

我想随机排列 col1 和 col2 中的数据,结果将是这样的:
id col1    col2     col3
1 data31 data22 data13
2 data11 data12 data23
3 data21 data32 data33

最佳答案

使用 DBMS_RANDOM 来实现随机性。子查询中的 ROW_NUMBER() 提供了一个 Hook ,您可以在 WHERE 子句中使用该 Hook ,否则您将获得一个 CROSS JOIN(这不是很随机,而且可能很大)。

with c1 as ( select col1
, row_number() over (order by dbms_random.value ) rn
from your_table )
, c2 as ( select col2
, row_number() over (order by dbms_random.value ) rn
from your_table )
, c3 as ( select col3
, row_number() over (order by dbms_random.value ) rn
from your_table )
select c1.col1
, c2.col2
, c3.col3
from c1, c2, c3
where c2.rn = c1.rn
and c3.rn = c1.rn;

为了获得最佳效果,请记住使用种子。 Find out more .

关于sql - 如何在 SQL (Oracle) 中随机排列数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15340179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com