如何在日期范围内复制name_id

时间:2019-06-25 13:46:55

标签: amazon-redshift

我试图获取一个名称ID的列表,并在25个月的范围内重复它们,因此,如果我有100个名称,我希望得到2500行。一般来说,我对SQL还是很陌生,所以在使用它时遇到了一些麻烦。

我正在使用查询根据表的行号生成日期的行。我使用的数据集没有与名称ID关联的日期,因此我无法加入它们。

select distinct to_date(date_part(month, d.n) 
|| '/' 
|| date_part(year, d.n), 'MM/YYYY') AS daten
select (getdate()::date - row_number() over (order by true))::date as n
from any_table) as d
where datediff(mm, daten, current_date) < 25

1 个答案:

答案 0 :(得分:1)

我想我知道您要实现的目标,但是您发布的查询对我不起作用。

基本上,如果要获取两个表的所有排列,则基本上要执行CROSS JOIN操作。

我将查询重新编写为您希望达到的目标。让我知道不是吗。

with months as (
    select to_char(dateadd(month, - row_number() over (), current_date), 'MM/YYYY') as month
    from base_zalon_backend.request
    limit 5 -- gives you last 5 months (including current month)
), ids as (
    select 'id_1' as id UNION ALL
    select 'id_2' union all
    select 'id_3' union all
    select 'id_4' union all
    select 'id_5'
)
select * from months cross join ids order by month, id

返回:

month   id
01/2019 id_1
01/2019 id_2
01/2019 id_3
01/2019 id_4
01/2019 id_5
02/2019 id_1
02/2019 id_2
02/2019 id_3
02/2019 id_4
02/2019 id_5
03/2019 id_1
03/2019 id_2
03/2019 id_3
03/2019 id_4
03/2019 id_5
04/2019 id_1
04/2019 id_2
04/2019 id_3
04/2019 id_4
04/2019 id_5
05/2019 id_1
05/2019 id_2
05/2019 id_3
05/2019 id_4
05/2019 id_5
相关问题