gpt4 book ai didi

sql - 使用 ORDER BY NEWID() 生成随机测试数据,包括重复的行

转载 作者:行者123 更新时间:2023-12-03 02:52:21 24 4
gpt4 key购买 nike

我需要从表中选择随机行作为测试数据。有时我需要的测试数据行数可能多于表中的记录数。重复的没问题。如何构建我的选择以便可以获得重复的行?

CREATE TABLE [Northwind].[dbo].[Persons]
(PersonID int, LastName varchar(255))

INSERT INTO [Northwind].[dbo].[Persons]
VALUES
(1, 'Smith'),
(2, 'Jones'),
(3, 'Washington')

SELECT TOP 5 *
FROM [Northwind].[dbo].[Persons]
ORDER BY NEWID()

如何让 Select 语句以随机顺序提供五个重复的记录?目前,它仅以随机顺序返回三个。

我希望能够扩展它以获取 100 行或 1000 行或我需要的任意数量。

最佳答案

使用递归 CTE 合并足够的行,使它们大于您想要的大小。然后像之前一样从中进行选择。

declare
@desired int = 5,
@actual int = (select count(*) from persons);

with

persons as (

select personId,
lastName,
batch = 0
from Persons

union all
select personId,
lastName,
batch = batch + 1
from persons
where (batch + 1) * @actual < @desired

)

select
top (@desired) personId, lastName
from persons
order by newid()

关于sql - 使用 ORDER BY NEWID() 生成随机测试数据,包括重复的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56066446/

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