【问题标题】:How to create dynamic column based on distance from specific date?如何根据与特定日期的距离创建动态列?
【发布时间】:2022-01-18 12:44:59
【问题描述】:

我想在 Redshift 中创建动态列,它将动态添加增加 1 的新值。基本上它会计算与特定日期的月份距离,比如 2020 年 1 月 1 日。所以本月应该是 23,下个月应该是 24 等等。是否有可能以某种方式替换我现在在 WITH 语句中拥有的静态内容?计数器在 12 停止,我必须每个月手动增加它。

with months as (
    select 1 as mon union all select 2 union all select 3 union all select 4 union all
    select 5 as mon union all select 6 union all select 7 union all select 8 union all
    select 9 as mon union all select 10 union all select 11 union all select 12
   ),

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    试试这个

       Alter table tablename
       Add New_column number Default
       datediff(mon,date_col, current_date);
    

    或者

      With data as
      (Select row_number()  over (order by 1) rn from 
      table)
     Select datediff(month, max(rn), current_date) 
      from data;
    

    注意:将表替换为某些表,其中条目计数超过您所需的 9 等,然后可以根据需要限制结果

    【讨论】:

      【解决方案2】:

      我认为您应该使用 DATEDIFF 函数,因为它可以为您提供两个日期之间的月差。只需输入您想要的日期:https://docs.aws.amazon.com/redshift/latest/dg/r_DATEDIFF_function.html

      示例: select datediff(mon,'2020-01-01',current_date) as mon_diff

      取决于表格的大小,也许将代码保存为视图,这样每次运行时都会得到正确的差异。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        相关资源
        最近更新 更多