Sql 如何使用配置单元从给定范围生成随机日期

Sql 如何使用配置单元从给定范围生成随机日期,sql,random,hive,hiveql,date-range,Sql,Random,Hive,Hiveql,Date Range,使用蜂箱。我需要从“2019-01-01”和“2019-10-31”之间的给定日期范围中选择随机日期。 有谁能指导我的查询吗?使用floor(rand*100)%N+1可以生成范围为1的随机自然数。。N.如果随机数是一位数,则使用lpad将前导0添加到字符串中,得到两个GIGIG,如01、02 演示: 结果: 2019-04-31 2019-07-10 2019-01-12 添加date()函数以解决不同月份中28、30-31天的问题。日期()将无效日期转换为最接近的有效日期: 例如,日期

使用蜂箱。我需要从“2019-01-01”和“2019-10-31”之间的给定日期范围中选择随机日期。 有谁能指导我的查询吗?

使用
floor(rand*100)%N+1
可以生成范围为1的随机自然数。。N.如果随机数是一位数,则使用lpad将前导0添加到字符串中,得到两个GIGIG,如01、02

演示:

结果:

2019-04-31
2019-07-10
2019-01-12
添加date()函数以解决不同月份中28、30-31天的问题。日期()将无效日期转换为最接近的有效日期: 例如,日期('2019-02-31')返回2019-03-03

总而言之:

select date(concat('2019','-',lpad(floor(RAND()*100.0)%10+1,2,0),'-',lpad(floor(RAND()*100.0)%31+1,2,0)));
结果:

2019-04-31
2019-07-10
2019-01-12
还有一个选项是用订单号生成所需的日期范围,并用随机数连接:

set hivevar:start_date=2019-01-01; 
set hivevar:end_date=2019-10-31; 

with date_range as 
(--this query generates date range with order number, max i=303 for this range 
select date_add ('${hivevar:start_date}',s.i) as dt, i 
  from ( select posexplode(split(space(datediff('${hivevar:end_date}','${hivevar:start_date}')),' ')) as (i,x) ) s
)

--join range generated with random number 0..303(check max in date_range)
select d.dt from date_range d inner join (select floor(RAND()*100.0)%304 as i) r on d.i=r.i;
结果:

2019-04-31
2019-07-10
2019-01-12
所有测试均在蜂箱中进行。

使用
地板(rand*100)%N+1
可以生成范围为1的随机自然数。。N.如果随机数是一位数,则使用lpad将前导0添加到字符串中,得到两个GIGIG,如01、02

演示:

结果:

2019-04-31
2019-07-10
2019-01-12
添加date()函数以解决不同月份中28、30-31天的问题。日期()将无效日期转换为最接近的有效日期: 例如,日期('2019-02-31')返回2019-03-03

总而言之:

select date(concat('2019','-',lpad(floor(RAND()*100.0)%10+1,2,0),'-',lpad(floor(RAND()*100.0)%31+1,2,0)));
结果:

2019-04-31
2019-07-10
2019-01-12
还有一个选项是用订单号生成所需的日期范围,并用随机数连接:

set hivevar:start_date=2019-01-01; 
set hivevar:end_date=2019-10-31; 

with date_range as 
(--this query generates date range with order number, max i=303 for this range 
select date_add ('${hivevar:start_date}',s.i) as dt, i 
  from ( select posexplode(split(space(datediff('${hivevar:end_date}','${hivevar:start_date}')),' ')) as (i,x) ) s
)

--join range generated with random number 0..303(check max in date_range)
select d.dt from date_range d inner join (select floor(RAND()*100.0)%304 as i) r on d.i=r.i;
结果:

2019-04-31
2019-07-10
2019-01-12
全部在蜂箱中测试