Получить день недели oracle
Я провел дни, пытаясь понять это безрезультатно, так что, надеюсь, кто-то может мне помочь. У меня есть запрашиваемый набор дат, который содержит несколько полей, включая столбец дат. Я хочу создать в своем запросе новое поле, в котором будет указано, что такое понедельник и пятница для недели конкретной даты в этой строке.
Так, например; если дата в одной из моих строк «16.01.18», в новом поле должно быть указано «1/15/18 - 19.01.18».
Таким образом, в основном мне нужно иметь возможность извлечь дату понедельника (15.01.18) и дату пятницы (19.01.18) недели 1/16/18, а затем объединить их с помощью тире (-) между. Мне нужно сделать это для каждого ряда.
Как же я могу это сделать? Я изо всех сил пытался выяснить, как найти понедельник или пятницу данной даты .
12.7 Date and Time Functions
This section describes the functions that can be used to manipulate temporal values. See Section 11.2, “Date and Time Data Types”, for a description of the range of values each date and time type has and the valid formats in which values may be specified.
Table 12.11 Date and Time Functions
Name | Description |
---|---|
ADDDATE() | Add time values (intervals) to a date value |
ADDTIME() | Add time |
CONVERT_TZ() | Convert from one time zone to another |
CURDATE() | Return the current date |
CURRENT_DATE() , CURRENT_DATE | Synonyms for CURDATE() |
CURRENT_TIME() , CURRENT_TIME | Synonyms for CURTIME() |
CURRENT_TIMESTAMP() , CURRENT_TIMESTAMP | Synonyms for NOW() |
CURTIME() | Return the current time |
DATE() | Extract the date part of a date or datetime expression |
DATE_ADD() | Add time values (intervals) to a date value |
DATE_FORMAT() | Format date as specified |
DATE_SUB() | Subtract a time value (interval) from a date |
DATEDIFF() | Subtract two dates |
DAY() | Synonym for DAYOFMONTH() |
DAYNAME() | Return the name of the weekday |
DAYOFMONTH() | Return the day of the month (0-31) |
DAYOFWEEK() | Return the weekday index of the argument |
DAYOFYEAR() | Return the day of the year (1-366) |
EXTRACT() | Extract part of a date |
FROM_DAYS() | Convert a day number to a date |
FROM_UNIXTIME() | Format Unix timestamp as a date |
GET_FORMAT() | Return a date format string |
HOUR() | Extract the hour |
LAST_DAY | Return the last day of the month for the argument |
LOCALTIME() , LOCALTIME | Synonym for NOW() |
LOCALTIMESTAMP , LOCALTIMESTAMP() | Synonym for NOW() |
MAKEDATE() | Create a date from the year and day of year |
MAKETIME() | Create time from hour, minute, second |
MICROSECOND() | Return the microseconds from argument |
MINUTE() | Return the minute from the argument |
MONTH() | Return the month from the date passed |
MONTHNAME() | Return the name of the month |
NOW() | Return the current date and time |
PERIOD_ADD() | Add a period to a year-month |
PERIOD_DIFF() | Return the number of months between periods |
QUARTER() | Return the quarter from a date argument |
SEC_TO_TIME() | Converts seconds to 'hh:mm:ss' format |
SECOND() | Return the second (0-59) |
STR_TO_DATE() | Convert a string to a date |
SUBDATE() | Synonym for DATE_SUB() when invoked with three arguments |
SUBTIME() | Subtract times |
SYSDATE() | Return the time at which the function executes |
TIME() | Extract the time portion of the expression passed |
TIME_FORMAT() | Format as time |
TIME_TO_SEC() | Return the argument converted to seconds |
TIMEDIFF() | Subtract time |
TIMESTAMP() | With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments |
TIMESTAMPADD() | Add an interval to a datetime expression |
TIMESTAMPDIFF() | Subtract an interval from a datetime expression |
TO_DAYS() | Return the date argument converted to days |
TO_SECONDS() | Return the date or datetime argument converted to seconds since Year 0 |
UNIX_TIMESTAMP() | Return a Unix timestamp |
UTC_DATE() | Return the current UTC date |
UTC_TIME() | Return the current UTC time |
UTC_TIMESTAMP() | Return the current UTC date and time |
WEEK() | Return the week number |
WEEKDAY() | Return the weekday index |
WEEKOFYEAR() | Return the calendar week of the date (1-53) |
YEAR() | Return the year |
YEARWEEK() | Return the year and week |
Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:
The query also selects rows with dates that lie in the future.
Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.
Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. (For our purposes, a single query also includes a call to a stored program (stored routine, trigger, or event) and all subprograms called by that program.) This principle also applies to CURDATE() , CURTIME() , UTC_DATE() , UTC_TIME() , UTC_TIMESTAMP() , and to any of their synonyms.
The CURRENT_TIMESTAMP() , CURRENT_TIME() , CURRENT_DATE() , and FROM_UNIXTIME() functions return values in the current session time zone, which is available as the session value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the session time zone. See Section 5.1.13, “MySQL Server Time Zone Support”.
Some date functions can be used with “ zero ” dates or incomplete dates such as '2001-11-00' , whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a nonzero value. For example:
Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:
Several functions are strict when passed a DATE() function value as their argument and reject incomplete dates with a day part of zero: CONVERT_TZ() , DATE_ADD() , DATE_SUB() , DAYOFYEAR() , TIMESTAMPDIFF() , TO_DAYS() , TO_SECONDS() , WEEK() , WEEKDAY() , WEEKOFYEAR() , YEARWEEK() .
Fractional seconds for TIME , DATETIME , and TIMESTAMP values are supported, with up to microsecond precision. Functions that take temporal arguments accept values with fractional seconds. Return values from temporal functions include fractional seconds as appropriate.
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD() . The related function SUBDATE() is a synonym for DATE_SUB() . For information on the INTERVAL unit argument, see Temporal Intervals.
When invoked with the days form of the second argument, MySQL treats it as an integer number of days to be added to expr .
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is a time expression.
CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given by to_tz and returns the resulting value. Time zones are specified as described in Section 5.1.13, “MySQL Server Time Zone Support”. This function returns NULL if the arguments are invalid.
If the value falls out of the supported range of the TIMESTAMP type when converted from from_tz to UTC, no conversion occurs. The TIMESTAMP range is described in Section 11.2.1, “Date and Time Data Type Syntax”.
To use named time zones such as 'MET' or 'Europe/Amsterdam' , the time zone tables must be properly set up. For instructions, see Section 5.1.13, “MySQL Server Time Zone Support”.
Returns the current date as a value in ' YYYY-MM-DD ' or YYYYMMDD format, depending on whether the function is used in string or numeric context.
Oracle реализует набор функций для работы со значениями типа даты/времени. Мы не будем подробно рассматривать все функции, но сводка в табл. 1 познакомит Вас с доступными возможностями. Если какие-то функции вас заинтересуют, обращайтесь за подробным описанием к справочнику Oracle SQL Reference.
Избегайте использования традиционных функций Oracle, обрабатывающих значения типа DATE , при работе с новыми типами данных TIMESTAMP . Вместо них следует по возможности использовать новые функции для типов INTERVAL . А DATE -функции должны использоваться только для обработки значений типа DATE .
Многие из приведенных в табл. 1 функций (в том числе ADD_MONTHS ) получают значения типа DATE . При использовании таких функций с новыми типами данных TIMESTAMP могут возникнуть проблемы. Хотя любой из этих функций можно передать значение типа TIMESTAMP , Oracle неявно преобразует его к типу DATE , и только тогда функция выполнит свою задачу, например:
В этом примере переменная ts содержит значение типа TIMESTAMP WITH TIME ZONE . Это значение неявно преобразуется в DATE при передаче LAST_DAY . Поскольку в типе DATE не сохраняются ни дробные части секунд, ни смещение часового пояса, эти части значения ts попросту отбрасываются. Результат LAST_DAY снова присваивается ts , что приводит к выполнению второго неявного преобразования — на этот раз DATE преобразуется в TIMESTAMP WITH TIME ZONE . Второе преобразование получает часовой пояс сеанса, поэтому в смещении часового пояса в итоговом значении мы видим ?05:00.
Очень важно понимать эти преобразования. и избегать их. Несомненно, вы представляете, какие коварные ошибки могут появиться в программе из-за неосторожного использования функций DATE со значениями TIMESTAMP . Честно говоря, я не представляю, почему в Oracle встроенные функции DATE не были перегружены для нормальной работы с TIMESTAMP . Будьте осторожны!
В Oracle мы получаем номер недели из следующего запроса:
Есть ли способ получить диапазон дат для данного номера недели?
Нет, это не так. Вы путаете 'IW' (который запускает MON - SUN) с 'WW' , который запускается с первого дня года:
Однако достаточно просто создать диапазон для номера недели IW. Вам нужно умножить номер IW на 7, который можно преобразовать в дату с маской дня года. Затем вы можете использовать функцию next_day() , чтобы получить предыдущий понедельник и следующее воскресенье относительно этой даты:
Очевидно, что это решение использует мои настройки NLS (на английском языке): вам может понадобиться настроить решение, если вы используете другие настройки.
Такие проблемы легко решить с помощью таблиц календаря.
Следующий запрос основан на предположении (ISO 8601), что 4 января присутствует в первую неделю года. Поэтому я могу сгенерировать правильную дату в первую неделю любого года, построив 4 января как: to_date(year || '-01-04', 'yyyy-mm-dd') . Oracle сообщит мне день недели (sun = 1, sat = 7) для любой даты, используя to_char(date, 'D') . 4 января 2017 года - среда (день 4). Вычитание 3 дней даст мне первый день (воскресенье) первой недели года. Теперь легко найти начальный день любой недели в году, просто добавив 7 дней для каждой недели (не считая первую неделю).
Редактировать: это «конвертировать» выражения, которые вам нужно конвертировать из недели в диапазон дат. Обратите внимание, что 2017 и 39 являются переменными .
Для первой и последней недели года этот запрос нуждается в некоторой логике CASE, но для других недель работает хорошо. Это решение использует текущие настройки NLS.
1) дата '2017-01-01' - в каком году мы ищем недели, или это может быть усеченный (sysdate, 'YEAR') первый день текущего года
3) trunc (. 'day') - дает дату первого дня недели
Вот запрос, чтобы перечислить все недели ISO с 2001 по 2099 год
Я использую эту функцию:
Пожалуйста, обратите внимание, что, согласно моим комментариям, это будет неоднозначно, если вы предоставите номер недели без года. Функция возвращает первый день данной недели ISO.
3 ответа
Предполагая, что ваш столбец имеет тип date , вы можете использовать trunc , чтобы получить первый день недели (понедельник), а затем добавить 4 дни, чтобы получить пятницу.
Чтобы отформатировать дату в виде строки в нужном формате, вы можете использовать to_char ; например:
Вы также можете использовать функцию NEXT_DAY , например:
Обратите внимание, что, используя вышеприведенное, в выходные дни понедельник будет понедельником, предшествующим текущей дате, а пятницу будет пятницей, следующей за текущей датой, то есть между двумя днями будет 11 дней.
Вы также можете использовать
В этом случае понедельник и пятница всегда будут с одной и той же недели, но если SYSDATE в выходные, возвращенный понедельник и пятница будут с ПРЕДЫДУЩЕЙ недели.
Для этого может существовать более простой, канонический метод Oracle, но вы все равно можете сократить его до простого вычисления в любом случае. Я предполагаю, что вы имеете дело только с датами, падающими с понедельника по пятницу. Если вам нужно иметь дело с датами выходных, вам, возможно, придется более четко указать, к какой логической неделе они должны быть прикреплены.
EXTRACT extracts and returns the value of a specified datetime field from a datetime or interval expression. The expr can be any expression that evaluates to a datetime or interval data type compatible with the requested field:
If YEAR or MONTH is requested, then expr must evaluate to an expression of data type DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE , TIMESTAMP WITH LOCAL TIME ZONE , or INTERVAL YEAR TO MONTH .
If DAY is requested, then expr must evaluate to an expression of data type DATE , TIMESTAMP , TIMESTAMP WITH TIME ZONE , TIMESTAMP WITH LOCAL TIME ZONE , or INTERVAL DAY TO SECOND .
If HOUR , MINUTE , or SECOND is requested, then expr must evaluate to an expression of data type TIMESTAMP , TIMESTAMP WITH TIME ZONE , TIMESTAMP WITH LOCAL TIME ZONE , or INTERVAL DAY TO SECOND . DATE is not valid here, because Oracle Database treats it as ANSI DATE data type, which has no time fields.
If TIMEZONE_HOUR , TIMEZONE_MINUTE , TIMEZONE_ABBR , TIMEZONE_REGION , or TIMEZONE_OFFSET is requested, then expr must evaluate to an expression of data type TIMESTAMP WITH TIME ZONE or TIMESTAMP WITH LOCAL TIME ZONE .
EXTRACT interprets expr as an ANSI datetime data type. For example, EXTRACT treats DATE not as legacy Oracle DATE but as ANSI DATE , without time elements. Therefore, you can extract only YEAR , MONTH , and DAY from a DATE value. Likewise, you can extract TIMEZONE_HOUR and TIMEZONE_MINUTE only from the TIMESTAMP WITH TIME ZONE data type.
When you specify TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value returned is a VARCHAR2 string containing the appropriate time zone region name or abbreviation. When you specify any of the other datetime fields, the value returned is an integer value of NUMBER data type representing the datetime value in the Gregorian calendar. When extracting from a datetime with a time zone value, the value returned is in UTC. For a listing of time zone region names and their corresponding abbreviations, query the V$TIMEZONE_NAMES dynamic performance view.
This function can be very useful for manipulating datetime field values in very large tables, as shown in the first example below.
Time zone region names are needed by the daylight saving feature. These names are stored in two types of time zone files: one large and one small. One of these files is the default file, depending on your environment and the release of Oracle Database you are using. For more information regarding time zone files and names, see Oracle Database Globalization Support Guide .
Some combinations of datetime field and datetime or interval value expression result in ambiguity. In these cases, Oracle Database returns UNKNOWN (see the examples that follow for additional information).
Oracle Database Globalization Support Guide for a complete listing of the time zone region names in both files
Appendix C in Oracle Database Globalization Support Guide for the collation derivation rules, which define the collation assigned to the character return value of EXTRACT
Datetime/Interval Arithmetic for a description of datetime_value_expr and interval_value_expr
Oracle Database Reference for information on the dynamic performance views
The following example returns from the oe.orders table the number of orders placed in each month:
The following example returns the year 1998.
The following example selects from the sample table hr.employees all employees who were hired after 2007:
The following example results in ambiguity, so Oracle returns UNKNOWN :
The ambiguity arises because the time zone numerical offset is provided in the expression, and that numerical offset may map to more than one time zone region name.
MySQL 5.7 Reference Manual Including MySQL NDB Cluster 7.5 and NDB Cluster 7.6
Читайте также: