是否可以在 oracle 中构造一个日历周加年的日期?
Is it possible to construct a date out of the calendar week plus year in oracle?
我有一个包含日历周加上年作为字符串的列,其构造方式如下
select TO_CHAR(TO_DATE('01.03.2020'),'WW/YYYY') from DUAL
这会产生类似
的字符串
09/2020
是否可以从这个字符串中重建日期?
我不在乎日期是一周的开始、一周的结束还是本周内的任何其他日期。
是这样的吗?
with test (col) as
(select '09/2020' from dual),
-- construct the whole year with week markers
whole_year as
(select to_date(substr(col, -4), 'yyyy') + level - 1 datum,
--
to_char(to_date(substr(col, -4), 'yyyy') + level - 1, 'ww') week
from test
connect by level <= add_months(to_date(substr(col, -4), 'yyyy'), 12) -
to_date(substr(col, -4), 'yyyy')
)
select min(datum)
from whole_year
where week = '09';
第 9 周的 whole_year
CTE 看起来像这样:
DATUM WE
---------- --
25.02.2020 08
26.02.2020 09 --> this
27.02.2020 09
28.02.2020 09
29.02.2020 09
01.03.2020 09
02.03.2020 09
03.03.2020 09
04.03.2020 10
05.03.2020 10
06.03.2020 10
这意味着我在上面发布的查询结果,returns
<snip>
12 select min(datum)
13 from whole_year
14 where week = '09';
MIN(DATUM)
----------
26.02.2020
SQL>
WW
格式代码计算从 1 月 1 日开始的 7 天周期,因此只需获取您所在年份的 1 月 1 日并添加正确数量的 7 天周期:
Oracle 设置:
CREATE TABLE table_name ( value ) AS
SELECT TO_CHAR( DATE '2020-03-01', 'WW/YYYY' ) FROM DUAL;
查询:
SELECT TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) - 1 ) * 7
AS first_day_of_week,
TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) ) * 7 - 1
AS last_day_of_week
FROM table_name
输出:
FIRST_DAY_OF_WEEK | LAST_DAY_OF_WEEK
:---------------- | :---------------
2020-02-26 | 2020-03-03
db<>fiddle here
我有一个包含日历周加上年作为字符串的列,其构造方式如下
select TO_CHAR(TO_DATE('01.03.2020'),'WW/YYYY') from DUAL
这会产生类似
的字符串09/2020
是否可以从这个字符串中重建日期? 我不在乎日期是一周的开始、一周的结束还是本周内的任何其他日期。
是这样的吗?
with test (col) as
(select '09/2020' from dual),
-- construct the whole year with week markers
whole_year as
(select to_date(substr(col, -4), 'yyyy') + level - 1 datum,
--
to_char(to_date(substr(col, -4), 'yyyy') + level - 1, 'ww') week
from test
connect by level <= add_months(to_date(substr(col, -4), 'yyyy'), 12) -
to_date(substr(col, -4), 'yyyy')
)
select min(datum)
from whole_year
where week = '09';
第 9 周的 whole_year
CTE 看起来像这样:
DATUM WE
---------- --
25.02.2020 08
26.02.2020 09 --> this
27.02.2020 09
28.02.2020 09
29.02.2020 09
01.03.2020 09
02.03.2020 09
03.03.2020 09
04.03.2020 10
05.03.2020 10
06.03.2020 10
这意味着我在上面发布的查询结果,returns
<snip>
12 select min(datum)
13 from whole_year
14 where week = '09';
MIN(DATUM)
----------
26.02.2020
SQL>
WW
格式代码计算从 1 月 1 日开始的 7 天周期,因此只需获取您所在年份的 1 月 1 日并添加正确数量的 7 天周期:
Oracle 设置:
CREATE TABLE table_name ( value ) AS
SELECT TO_CHAR( DATE '2020-03-01', 'WW/YYYY' ) FROM DUAL;
查询:
SELECT TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) - 1 ) * 7
AS first_day_of_week,
TO_DATE( SUBSTR( value, 4 ), 'YYYY' ) + ( SUBSTR( value, 1, 2 ) ) * 7 - 1
AS last_day_of_week
FROM table_name
输出:
FIRST_DAY_OF_WEEK | LAST_DAY_OF_WEEK :---------------- | :--------------- 2020-02-26 | 2020-03-03
db<>fiddle here