【问题标题】:To find data from maximum date to last 12 month in SQL redshift在 SQL redshift 中查找从最大日期到过去 12 个月的数据
【发布时间】:2020-04-09 07:38:36
【问题描述】:

我在表中有一个字符串列(year_to_month),其值为 YYYYMM 格式。我必须找到最大 year_to_month 到持续 12 个月之间的数据。我已经尝试过下面的代码,但它不工作并且选择了一些随机的垃圾值,因为 year_to_month 中没有日期值

  select * from Table
  where to_date between to_date(year_to_month,'mm') between max(to_date(year_to_month,'mm'))-12 and 
  max(to_date(year_to_month,'mm'))

sample data
201911
201910
201909
201812
201802
201805

我正在使用 Amazon Redshift 数据库并在工作台中运行查询

谁能帮我看看我做错了什么?

【问题讨论】:

  • 抱歉,您的要求不清楚。鉴于上述样本数据,您想要什么结果?
  • 您好,我注意到您尚未接受任何答案,但您已经提出了五个问题。请记住接受对您最有帮助的答案。

标签: sql date amazon-redshift


【解决方案1】:

这就足够了:

select *
from Table
where to_date >= to_char(year_to_month,'yyyymm')

您不必与数据中的最大 year_to_month 进行比较,因为无论如何您都会得到所有这些值。

【讨论】:

    【解决方案2】:

    以下是我的方法:

    select newdate
    from (select to_date(year_to_month,'yyyymm') as newdate from sample) t
    where newdate
    between
    (
    select to_date(year_to_month,'yyyymm') - interval '12' month
    from
    (
      select t.*, row_number() over (order by year_to_month desc) as rn
      from sample t
    )
    where rn = 1
    )
    and 
    (
    select to_date(year_to_month,'yyyymm') 
    from
    (
      select t.*, row_number() over (order by year_to_month desc) as rn
      from sample t
    )
    where rn = 1
    )
    

    澄清:

    1,我使用下面的子查询来选择最大日期。

    select ...
    from
    (
      select t.*, row_number() over (order by year_to_month desc) as rn
      from sample t
    )
    where rn = 1
    

    2,我使用下面的查询来获取 12 个月之前的日期

    select to_date(year_to_month,'yyyymm') - interval '12' month
    

    测试结果(我在 Oracle 18c 中测试过。如果您在 Amazon Redshift 中遇到任何问题,请告诉我):

    DB<>Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2019-07-10
      相关资源
      最近更新 更多