获取sql中最近15天的日期列表

hm2xizp9  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(569)

sql能否在单个查询中获取最近15天的日期列表?
我们今天可以和你约会 select current_date() 我们还可以得到最后15天的日期 select date_add(current_date(), -15) 但如何显示最近15天的日期列表?例如,输出为

2020-05-17, 
2020-05-18, 
2020-05-19, 
2020-05-20, 
2020-05-21, 
2020-05-22, 
2020-05-23, 
2020-05-24, 
2020-05-25, 
2020-05-26, 
2020-05-27, 
2020-05-28, 
2020-05-29, 
2020-05-30, 
2020-05-31
qeeaahzv

qeeaahzv1#

在配置单元或spark sql中:

select date_add (date_add(current_date,-15),s.i) as dt 
  from ( select posexplode(split(space(15),' ')) as (i,x)) s

结果:

2020-05-18
2020-05-19
2020-05-20
2020-05-21
2020-05-22
2020-05-23
2020-05-24
2020-05-25
2020-05-26
2020-05-27
2020-05-28
2020-05-29
2020-05-30
2020-05-31
2020-06-01
2020-06-02

另请参见此答案。

jfewjypa

jfewjypa2#

WITH 
cte AS ( SELECT 1 num UNION ALL SELECT 2 UNION ALL ... UNION ALL SELECT 15 )
SELECT DATEADD(CURRENT_DATE(), -num)
FROM cte;

或者,举个例子

WITH 
cte1 AS ( SELECT 1 num UNION ALL 
          SELECT 2 UNION ALL 
          SELECT 3 UNION ALL 
          SELECT 4 UNION ALL 
          SELECT 5 ),
cte2 AS ( SELECT 0 num 
          UNION ALL SELECT 1 
          UNION ALL SELECT 2 )
SELECT DATEADD(CURRENT_DATE(), -cte1.num - cte2.num * 5)
FROM cte1, cte2;

相关问题