从另一个随机化的日期字段提交的计算日期

时间:2013-05-23 07:52:54

标签: sql tsql

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

我需要的是我有一个名为请求日期的列,此日期应该随机化,但比订单日期晚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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

使用其他声明

添加新变量
declare @od datetime

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

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

在insert语句中使用此变量,所以

,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 fiddle