简体   繁体   English

从 Hive 的日期范围中选择日期(每个月的第一天)

[英]Selecting date(1st of every month) from a date range in Hive

Need to generate random date(1st of every month) selected from a given date range in hive (inclusive range).需要生成从给定日期范围 hive(含范围)中选择的随机日期(每个月的第一天)。 For example if range is 25/12/2021 - 01/06/2022, then I want to select random date from this set of dates{01/01/2022, 01/02/2022, 01/03/2022, 01/04/2022, 01/05/2022, 01/06/2022).例如,如果范围是 25/12/2021 - 01/06/2022,那么我想从这组日期中随机抽取 select {01/01/2022, 01/02/2022, 01/03/2022, 01/ 04/2022、01/05/2022、01/06/2022)。

Can any one guide me with my query?任何人都可以指导我的查询吗?

I tried using我尝试使用

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

but this needs date, I need to pass a column value as low range and a particular date as 2nd range.但这需要日期,我需要传递一个列值作为低范围和一个特定日期作为第二个范围。 Since there are different dates for different columns for the low range to b passed.由于要通过的低范围对于不同的列有不同的日期。

You can use below code to calculate a random date between two dates.您可以使用以下代码计算两个日期之间的随机日期。

select trunc(date_add(start_dt, cast (datediff( end_dt,start_dt)*rand() as INT)),'MM') as random_dt

You can test the logic using below code-您可以使用以下代码测试逻辑 -

select trunc(date_add('2021-01-17', cast (datediff( '2022-01-27','2021-01-17')*rand() as INT)), 'MM') as random_dt

Explanation -解释 -
Idea is to add a random number that is less than date difference to the start date.想法是向开始日期添加一个小于日期差的随机数。
datediff() - This returns diff of date as INT. datediff() - 这会将日期差异作为 INT 返回。
rand() - This returns a number between 0,1(both included). rand() - 这将返回 0,1 之间的数字(均包含在内)。 Which means, your start or end date can be same as random date sometime.这意味着,您的开始或结束日期有时可以与随机日期相同。
date_add - This adds the random integer to the start date to generate random date. date_add - 这会将随机的 integer 添加到开始日期以生成随机日期。 trunc(dt,'MM') - is going to return first day of the month. trunc(dt,'MM') - 将返回该月的第一天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM