在Teradata查询中声明参数或If-then-else

时间:2017-04-17 18:04:29

标签: if-statement parameters teradata

我是Teradata的新手。情况如下:

如果Current_date是<那么15个月?Startdate parameter =上个月的第1个和?EndDate param =当前月的最后日期

SELECT ... FROM ViewA
WHERE date BETWEEN ?Startdate AND ?EndDate 

ELSE如果Current_date> = 15则Startdate参数=当前月份的第1天和EndDate参数=当月的最后日期

SELECT ... FROM ViewA
WHERE date BETWEEN ?Startdate AND ?EndDate 

我能够计算每种情况下的日期,但无法弄清楚:

#1)如何将它们放入参数中。如果我可以将它们放入参数中,那么我所要做的就是

SELECT ... FROM ViewA
WHERE date BETWEEN ?Startdate AND ?EndDate 

OR  #2)写一个IF-THEN-ELSE

If Current_date is < 15 of month

    SELECT ... FROM ViewA
        WHERE Date BETWEEN 
        ADD_MONTHS((DATE - EXTRACT(DAY FROM DATE)+1), -1) AND ADD_MONTHS(LAST_DAY(DATE),0)
    ELSE
    SELECT ... FROM ViewA
        WHERE date BETWEEN 
        ADD_MONTHS((DATE - EXTRACT(DAY FROM DATE)+1), 0)  AND ADD_MONTHS(LAST_DAY(DATE),0) )

END IF

请指导如何实现#1或#2。我无法在teradata中创建函数或存储过程

2 个答案:

答案 0 :(得分:0)

#2以日历为例。

SELECT calendar_date from Sys_Calendar.CALENDAR
    WHERE calendar_date
       BETWEEN
         case when extract (day from current_date) < 15
                 then ADD_MONTHS((current_date - EXTRACT(DAY FROM current_date)+1), -1)
                 else             current_date - EXTRACT(DAY FROM current_date)+1
         end
       AND ADD_MONTHS(LAST_DAY(current_date),0)
    order by calendar_date
    ;

我更喜欢current_date,不能与数据类型混淆。

答案 1 :(得分:0)

WHERE date 
BETWEEN Trunc(current_date - 14 , 'mon') -- first day of the month 14 days before today 
    AND last_day(current_date)           -- last day of current month