0

我必须创建一些随机数据,到目前为止,在这个论坛的帮助下,我已经完成了 80%,但我现在(再次)陷入困境

我需要的是我有一个名为 Requested Date 的列,这个日期应该是随机的,但比订单日期晚 1 到 10 天。这可以做到吗?

DECLARE @OrderNumber varchar (30)
DECLARE @OrderDate int
DECLARE @OrderLineNumber varchar(50)
DECLARE @CustomerSkey int
DECLARE @ProductSkey int
DECLARE @OrderMethodSkey int
DECLARE @Quantity int
DECLARE @Cost Decimal(18,3)
DECLARE @RequestedDate int

SET @OrderNumber = 1
SET @OrderDate = 0
SET @OrderLineNumber = 1
SET @CustomerSkey = 1
SET @ProductSkey = 1
SET @OrderMethodSkey = 1
SET @Quantity = 1
SET @Cost = 1
SET @RequestedDate = 0


WHILE @OrderNumber <= 100
WHILE @OrderDate <= 100
WHILE @OrderLineNumber <= 100
WHILE @CustomerSkey <= 100
WHILE @ProductSkey <= 100
WHILE @OrderMethodSkey <= 100
WHILE @Quantity <= 100
WHILE @Cost <= 100
WHILE @RequestedDate <= 100


BEGIN
INSERT INTO Orders 
(OrderNumber
, OrderDate
, OrderLineNumber
, CustomerSkey
, ProductSkey
, OrderMethodSkey
, OrderTime
, Quantity
, Cost
, RequestedDate)

SELECT 
'ORD' + Right ('000000' + CAST (@OrderNumber AS varchar (30)), 6)
,DATEADD (day, CAST (RAND () * 1500 as int), '2008-1-1')
,(Right ('0' + CAST (@OrderLineNumber AS varchar (30)), 6))
,(99 * RAND()) + 1
,(99 * RAND()) + 1
,(2 * RAND()) + 1
,DATEADD(ms, cast(86400000 * RAND() as int), convert(time, '00:00'))
,(190 * RAND()) + 10
,(40 * RAND()) + 10
,DATEADD (day, CAST (RAND () * 10 as int), @RequestedDate)




SET @OrderNumber = @OrderNumber + 1
SET @OrderDate = @OrderDate + 1
SET @OrderLineNumber = @OrderLineNumber + 1
SET @CustomerSkey = @CustomerSkey + 1
SET @ProductSkey = @ProductSkey + 1
SET @OrderMethodSkey = @OrderMethodSkey + 1
SET @Quantity = @Quantity + 1
SET @Cost = @Cost + 1
SET @RequestedDate = @RequestedDate + 1

END
4

2 回答 2

0

在 PostgreSQL 中,您可以执行以下操作:

with t as (select '2013-01-01'::date as order_date)

select 
   order_date, 
   (order_date + round(.5 + 10*random()) * interval '1 day')::date as requested_date,
   (order_date + round(.5 + 10*random()) * interval '1 day')::date - order_date as difference  from t

0)random()函数返回 0 到 1 之间的随机数

1)round(.5 + 10*random()会给你1到10之间的数字

2) 随机数以天为间隔添加到日期

3) 结果被转换为日期(因为第 2 步将返回时间戳)

为了证明round(.5 + 10*random()得到 1 到 10 之间的随机数:

with t as (select round(.5 + 10*random()) rnd from generate_series(1,1000000,1))
select rnd, count(*) cnt from t group by rnd order by rnd

rnd      cnt
  1   100249
  2   100817
  3    99550
  4    99813
  5   100065
  6    99468
  7   100089
  8    99652
  9    99889
 10   100408
于 2013-05-23T08:17:22.930 回答
0

您可以在插入语句之前计算 order_date 的值

使用其他声明添加一个新变量

declare @od datetime

在 while 循环内但在插入语句设置订单日期之前

select @od = DATEADD (day, CAST (RAND () * 1500 as int), '2008-1-1')

在插入语句中使用这个变量

,DATEADD (day, CAST (RAND () * 1500 as int), '2008-1-1')

变成

,@od

并使用此值计算请求日期,因此变为

,DATEADD (day, CAST (RAND () * 10 as int), @RequestedDate)

,DATEADD (day, CAST (RAND () * 10 as int), @od)

sql小提琴

于 2013-05-25T08:59:07.580 回答