我正在进行数据转换,我需要获取给定一周的开始和结束日期。
我的来源将日期存储在单个int
列'year_wk'
中。
此列的示例是
201201 - 表示 2012 年的第一周 201005 - 表示 2010 年的第五周
我想以标准mm/dd/yyyy
格式获取给定一周的开始和结束日期。
所以 201201 会给我类似 2012 年 1 月 1 日和 2012 年 1 月 7 日的信息。
它不会很漂亮,也可能不是非常有效,但您可以利用视图SYS_CALENDAR.CALENDAR
。我特意在示例中使用,这样您就可以使用作为所有 Teradata 安装的默认数据库SELECT *
的视图查看所有可用的属性:SYS_CALENDAR.CALENDAR
SELECT *
FROM Sys_Calendar."CALENDAR"
WHERE Year_of_Calendar = CAST(SUBSTRING('201201' FROM 1 FOR 4) AS INTEGER)
AND Week_of_Year = CAST(SUBSTRING('201201' FROM 5 FOR 2) AS INTEGER)
UNION
SELECT *
FROM Sys_Calendar."CALENDAR"
WHERE Year_of_Calendar = CAST(SUBSTRING('201005' FROM 1 FOR 4) AS INTEGER)
AND Week_of_Year = CAST(SUBSTRING('201005' FROM 5 FOR 2) AS INTEGER);
我不熟悉 Teradata,但这是 Oracle ISO 周查询,其中包含 2013 年全年的开始和结束日期。这应该适用于任何 SQL。对于非 iso 周,将周格式更改为 WW - 忘记在查询中将 mydate 重命名为 start_date:
SELECT mydate -- 1/1/2013 --
, TRUNC(mydate, 'iw') wk_starts
, TRUNC(mydate, 'iw') + 7 - 1/86400 wk_ends
, TO_NUMBER (TO_CHAR (mydate, 'IW')) ISO_wk#_iw
, TRUNC(mydate, 'w') week_start_date
, TRUNC(mydate, 'w') + 7 - 1/86400 AS week_end_date
FROM
(
SELECT TRUNC(SYSDATE, 'YEAR')-1 + LEVEL AS mydate -- 11/1/2013 --
FROM dual
CONNECT BY LEVEL <=
(-- First day of next year - first day of curr year --
SELECT TRUNC(ADD_MONTHS (SYSDATE, 12), 'Y')-TRUNC(SYSDATE, 'Y') "Num of Days"
FROM dual
)
)
/
SQL>
START_DATE WK_STARTS WK_ENDS ISO_WK#
------------------------------------------------------------------
1/1/2013 12/31/2012 1/6/2013 11:59:59 PM 1
1/2/2013 12/31/2012 1/6/2013 11:59:59 PM 1
...
...
1/7/2013 1/7/2013 1/13/2013 11:59:59 PM 2
1/8/2013 1/7/2013 1/13/2013 11:59:59 PM 2
...
...
1/14/2013 1/14/2013 1/20/2013 11:59:59 PM 3
1/15/2013 1/14/2013 1/20/2013 11:59:59 PM 3
周数日历:http ://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
下面是一些 SQL 代码,它将构建一个给定年份的开始和结束日期表。
如果您为所有相关年份构建此表,其余部分应通过 JOIN 语句完成
-- Create weekrange table
Create table Weekrange
(YearNo INT,
WeekNo INT,
StartDay DATETIME,
EndDay DATETIME)
-- Populate first row
insert into WeekRange
select 2013,1, DateAdd(d,-DATEPART(dw,'1/1/2013'),'1/1/2013')+1 as FirstDay,null -- Compute first day
update Weekrange set EndDay = DATEADD(D,6,StartDay) -- Determine last day
-- Add next 52 rows
declare @id INT
set @id=2
while @id <=53
begin
insert into Weekrange (YearNo,WeekNo) values (2013,@id)
set @id=@id+1
update Weekrange
set StartDay = DATEADD(D,1,xx.EndDay),
EndDay = DATEADD(D,7,xx.EndDay)
from
(select * from WeekRange ) xx
where xx.weekno=weekrange.WeekNo-1
end
select * from Weekrange
试图改进我的 SQL,这将是一个简单的灵魂:
SELECT CALENDAR_DATE,DAY_OF_WEEK
FROM SYS_CALENDAR.CALENDAR TERADATA
WHERE SUBSTR(CAST((CAST(CALENDAR_DATE AS DATE FORMAT 'MMDDYYYY')) AS VARCHAR(8) ),5,4) = '2010'
AND WEEK_OF_YEAR='05'
AND DAY_OF_WEEK IN (1,7)
ORDER BY CALENDAR_DATE
SELECT TD_WEEK_END (date) - 6
这TD_WEEK_END (date)
是周末的结束。只需从日期中减去 6 即可获得一周的开始。
注意:此答案集将始终返回星期日,因为星期日是一周的第一天。