使用 Teradata 创建具有设置行数的空输出 table

Create empty output table with set number of rows with Teradata

我知道我将如何使用 SAS 之类的东西来做到这一点,但是如果我想创建一个 table 其行数与从该语句派生的月份间隔一样多:

cast((cast(2017-03-31 as date) - cast(2016-01-31 as date) month(4)) as int) as date_range

..给出这样的输出:

2017-03-31
2017-02-28
2017-01-31
2017-12-31
2017-11-30
2017-10-31
2017-09-30
2017-08-31
2017-07-31
2017-06-30
2017-05-31
2017-04-30

在 Teradata 中执行此操作需要什么语句?

谢谢

获取月份的第一天更安全,因为将月份添加到该月的最后一天可能会出现问题(如果您以“2016-02-29”开始,您将获得后续月份的第 29 天)。

你可以用递归 cte 做你想做的事:

with recursive cte(dte) as (
        select cast('2016-02-01' as date)
        union all
        select add_months(cte.dte, 1)
        from cte
        where dte <= '2017-05-01'
    ),
    dates as (
        select dte - interval '1 day'
        from cte
    )
. . .

这些日期是根据现有列计算的吗?

或者您只需要那个列表?

在这两种情况下,您都可以利用 Teradata 的专有 EXPAND ON 功能:

SELECT BEGIN(pd)
FROM SYS_CALENDAR.CALENDAR  -- your table here
WHERE calendar_date = DATE  -- EXPAND requires FROM, so this is just to get a single row
EXPAND ON PERIOD(date '2016-01-31'      -- start date
                ,date '2017-03-31' + 1  -- end date (+1 because it's not included in the date range)
                ) AS pd BY ANCHOR PERIOD MONTH_END -- one row for each month end within the period