我正在进行数据转换,我需要获取给定周的开始和结束日期。
我的来源将日期存储在一个int
列'year_wk'
中。
此列的示例为
201201 - 意味着2012年的第一周 201005 - 意味着2010年的第五周
我希望以标准mm/dd/yyyy
格式获取给定周的开始日期和结束日期。
所以201201会给我一些类似于2012年1月1日和2012年1月1日的内容。
答案 0 :(得分:3)
它不会很漂亮,可能效率不高,但您可以利用视图SYS_CALENDAR.CALENDAR
。我故意在示例中使用SELECT *
,因此您可以使用SYS_CALENDAR.CALENDAR
视图查看所有可用的属性,该视图是所有Teradata安装的默认数据库:
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);
答案 1 :(得分:2)
我不熟悉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
答案 2 :(得分:1)
这是一些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
答案 3 :(得分:0)
尝试改进我的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
答案 4 :(得分:-1)
SELECT TD_WEEK_END (date) - 6
TD_WEEK_END (date)
是周末的结束。只需从日期中减去6即可得到一周的开头。
注意:此答案集将始终在星期日返回,因为星期日是一周的第一天。