【问题标题】:How to use variables inside functions in Redshift?如何在 Redshift 的函数中使用变量?
【发布时间】:2022-01-18 15:00:54
【问题描述】:

是否可以使用例如像这样排队

SELECT  trunc(dateadd(month,mon,add_months(date_trunc('month', CURRENT_DATE), -9))) as dates
FROM    months

而不是 -9,我希望有像这样创建的列的最大值(因此在本例中为 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

在 Redshift 中是否有可能?我就这样尝试过

SELECT  trunc(dateadd(month,mon,add_months(date_trunc('month', CURRENT_DATE), -MAX(mon))) as dates
FROM    months

但它没有按预期工作

【问题讨论】:

  • 这个mon 字段是在哪里创建的?如果您在主表中使用mon 列的最大值创建一个列,然后在函数中使用生成的列会怎样——这有帮助吗?
  • 您真正想要完成什么(而不是如何您试图做到这一点)?你想要9个月前的约会吗?你能描述一下你真正想要达到的输出吗?

标签: sql amazon-web-services amazon-redshift


【解决方案1】:

是的,另一种方法是

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

您可以根据需要使用具有更多条目的更大表,并在 WITH 子句中替换该表名,就像您在上述情况下所说的 max 9 一样,并将它们限制为您的表月条目数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2018-08-10
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2023-02-23
    • 2020-06-14
    相关资源
    最近更新 更多