我知道如何用SAS之类的东西来做这件事,但是如果我想创建一个表格,其行数与从该语句中得到的月份间隔一样多:
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中我需要做什么声明?
由于
答案 0 :(得分:1)
获得本月的第一天更安全,因为在月份的最后一天添加月份可能会有问题(如果您开始使用' 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
)
. . .
答案 1 :(得分:1)
这些日期是根据现有列进行计算的吗?
或者你只需要那份清单?
在这两种情况下,您都可以使用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