Как выбрать месяц из даты sql
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.
3 Ways to Extract the Month from a Date in SQL Server (T-SQL)
Here are three T-SQL functions that you can use to extract the month from a date in SQL Server.
MONTH()
The most obvious function to use is the MONTH() function. This function accepts one argument: the date.
DATEPART()
The DATEPART() function accepts two arguments: the first argument is the part of the date that you want to extract, and the second argument is the actual date that you want to extract it from.
In this example I used month as the first argument. You also have the option of using mm or m . Whichever one you use, the result is the same.
How to Extract Month from Date in SQL
Summary: in this tutorial, you will learn how to extract the month from a date in SQL by using some date functions.
To extract the month from a particular date, you use the EXTRACT() function. The following shows the syntax:
In this syntax, you pass the date from which you want to extract the month to the EXTRACT() function. The date can be a date literal or an expression that evaluates to a date value.
The EXTRACT() function returns a number which represents the month of the date.
The following example illustrates how to extract the month from the date of August 1st 2018 :
The result is 8 as we expected:
To get the current month, you use the CURRENT_TIMESTAMP function and pass it to the EXTRACT() function as follows:
The EXTRACT() function is a SQL standard function supported by MySQL, Oracle, and PostgreSQL.
If you use SQL Server, you can use the MONTH() or DATEPART() function to extract the month from a date.
For example, the following statement returns the current month in SQL Server:
Similar to SQL Server, MySQL also supports the MONTH() function to return the month from a date.
SQLite does not support EXTRACT() , MONTH() or DATEPART() function. To extract a month from a date, you use the strftime() function as follows:
In this tutorial, you have learned how to use various functions to extract the month from a date in SQL.
EXTRACT — извлечение из даты части (год, месяц, день. )
Функция extract получает из значений даты/времени поля, такие как год или час. Здесь source — значение типа timestamp , time или interval . (Выражения типа date приводятся к типу timestamp , так что допускается и этот тип.) Указанное поле представляет собой идентификатор, по которому из источника выбирается заданное поле. Функция extract возвращает значения типа numeric . Допустимые поля:
century
| # | date_part |
|---|---|
| 1 | 20 |
| # | date_part |
|---|---|
| 1 | 21 |
Первый век начался 0001-01-01 00:00:00, хотя люди в то время и не считали так. Это определение распространяется на все страны с григорианским календарём. Века с номером 0 не было; считается, что 1 наступил после -1. Если такое положение вещей вас не устраивает, направляйте жалобы по адресу: Ватикан, Собор Святого Петра, Папе.
Для значений timestamp это день месяца (1–31); для значений interval — число дней
| # | date_part |
|---|---|
| 1 | 16 |
| # | date_part |
|---|---|
| 1 | 40 |
decade
Год, делённый на 10
| # | date_part |
|---|---|
| 1 | 200 |
День недели, считая с воскресенья (0) до субботы (6)
| # | date_part |
|---|---|
| 1 | 5 |
Заметьте, что в extract дни недели нумеруются не так, как в функции to_char(. ‘D’).
День года (1–365/366)
| # | date_part |
|---|---|
| 1 | 47 |
epoch
Для значений timestamp with time zone это число секунд с 1970-01-01 00:00:00 UTC (отрицательное для предшествующего времени); для значений date и timestamp — номинальное число секунд с 1970-01-01 00:00:00 без учёта часового пояса, переходов на летнее время и т. п.; для значений interval — общее количество секунд в интервале
| # | date_part |
|---|---|
| 1 | 982384720.12 |
| # | date_part |
|---|---|
| 1 | 982355920.12 |
| # | date_part |
|---|---|
| 1 | 442800 |
Преобразовать время эпохи назад, в значение timestamp with time zone, с помощью to_timestamp можно так:
| # | to_timestamp |
|---|---|
| 1 | 2001-02-17 10:38:40.12+06 |
Имейте в виду, что применяя to_timestamp к времени эпохи, извлечённому из значения date или timestamp, можно получить не вполне ожидаемый результат: эта функция подразумевает, что изначальное значение задано в часовом поясе UTC, но это может быть не так.
| # | date_part |
|---|---|
| 1 | 20 |
isodow
День недели, считая с понедельника (1) до воскресенья (7)
| # | date_part |
|---|---|
| 1 | 7 |
Результат отличается от dow только для воскресенья. Такая нумерация соответствует ISO 8601.
isoyear
Год по недельному календарю ISO 8601, в который попадает дата (неприменимо к интервалам)
| # | date_part |
|---|---|
| 1 | 2005 |
| # | date_part |
|---|---|
| 1 | 2006 |
Год по недельному календарю ISO начинается с понедельника недели, в которой оказывается 4 января, так что в начале января или в конце декабря год по ISO может отличаться от года по григорианскому календарю. Подробнее об этом рассказывается в описании поля week.
Этого поля не было в PostgreSQL до версии 8.3.
julian
Юлианская дата, соответствующая дате или дате/времени (для интервала не определена). Значение будет дробным, если заданное время отличается от начала суток по местному времени. За дополнительной информацией обратитесь к Разделу B.7.
| # | date_part |
|---|---|
| 1 | 2453737 |
| # | date_part |
|---|---|
| 1 | 2453737.5 |
microseconds
Значение секунд с дробной частью, умноженное на 1 000 000; заметьте, что оно включает и целые секунды
| # | date_part |
|---|---|
| 1 | 28500000 |
millennium
| # | date_part |
|---|---|
| 1 | 3 |
Годы 20 века относятся ко второму тысячелетию. Третье тысячелетие началось 1 января 2001 г.
milliseconds
Значение секунд с дробной частью, умноженное на 1 000; заметьте, что оно включает и целые секунды.
| # | date_part |
|---|---|
| 1 | 28500 |
minute
| # | date_part |
|---|---|
| 1 | 38 |
month
Для значений timestamp это номер месяца в году (1–12), а для interval — остаток от деления числа месяцев на 12 (0–11)
| # | date_part |
|---|---|
| 1 | 2 |
| # | date_part |
|---|---|
| 1 | 3 |
| # | date_part |
|---|---|
| 1 | 1 |
quarter
Квартал (1–4), к которому относится дата
| # | date_part |
|---|---|
| 1 | 1 |
second
Секунды, включая дробную часть
| # | date_part |
|---|---|
| 1 | 40 |
| # | date_part |
|---|---|
| 1 | 28.5 |
timezone
Смещение часового пояса от UTC, представленное в секундах. Положительные значения соответствуют часовым поясам к востоку от UTC, а отрицательные — к западу. (Строго говоря, в Postgres Pro используется не UTC, так как секунды координации не учитываются.)
timezone_hour
Поле часов в смещении часового пояса
timezone_minute
Поле минут в смещении часового пояса
Номер недели в году по недельному календарю ISO 8601. По определению, недели ISO 8601 начинаются с понедельника, а первая неделя года включает 4 января этого года. Другими словами, первый четверг года всегда оказывается в 1 неделе этого года.
В системе нумерации недель ISO первые числа января могут относиться к 52-ой или 53-ей неделе предыдущего года, а последние числа декабря — к первой неделе следующего года. Например, 2005-01-01 относится к 53-ей неделе 2004 г., а 2006-01-01 — к 52-ей неделе 2005 г., тогда как 2012-12-31 включается в первую неделю 2013 г. Поэтому для получения согласованных результатов рекомендуется использовать поле isoyear в паре с week.
| # | date_part |
|---|---|
| 1 | 7 |
Поле года. Учтите, что года 0 не было, и это следует иметь в виду, вычитая из годов нашей эры годы до нашей эры.
| # | date_part |
|---|---|
| 1 | 2001 |
Примечание
С аргументом +/-бесконечность extract возвращает +/-бесконечность для монотонно увеличивающихся полей (epoch, julian, year, isoyear, decade, century и millennium). Для других полей возвращается NULL. До версии 9.6 Postgres Pro возвращал ноль для всех случаев с бесконечными аргументами.
Функция extract в основном предназначена для вычислительных целей. Функции форматирования даты/времени описаны в Разделе 9.8.
Функция date_part эмулирует традиционный для Ingres эквивалент стандартной SQL-функции extract:
date_part(‘поле’, источник)
Заметьте, что здесь параметр поле должен быть строковым значением, а не именем. Функция date_part воспринимает те же поля, что и extract. По историческим причинам функция date_part возвращает значения типа double precision. В некоторых случаях это может привести к потере точности. Поэтому вместо неё рекомендуется использовать функцию extract.