Datetime (transact-sql)datetime (transact-sql)
Содержание:
- TIME_FORMAT(time,format)
- CONVERT_TZ(dt,from_tz,to_tz)
- SQL References
- DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)
- Recommended Reading
- Using DATETIME in SQL
- SQL Учебник
- STR_TO_DATE(str,format)
- UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
- SQL Working with Dates
- АргументыArguments
- Working With SQL Dates
- TIMESTAMPADD(unit,interval,datetime_expr)
- Типы данных Access
- Функции для вычисления разницы между моментами
- PostgreSQL
- Пример
- DATE_FORMAT(date,format)
- Функции, характеризующие момент (значение аргумента)
- WEEK(date[,mode])
- SQL Справочник
TIME_FORMAT(time,format)
This function is used like the DATE_FORMAT() function, but the format string may contain format specifiers only for hours, minutes and seconds.
If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0 to 23. The other hour format specifiers produce the hour value modulo 12.
mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l'); +---------------------------------------------------------+ | TIME_FORMAT('100:00:00', '%H %k %h %I %l') | +---------------------------------------------------------+ | 100 100 04 04 4 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
CONVERT_TZ(dt,from_tz,to_tz)
This 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. This function returns NULL if the arguments are invalid.
mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','GMT','MET') | +---------------------------------------------------------+ | 2004-01-01 13:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00'); +---------------------------------------------------------+ | CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00') | +---------------------------------------------------------+ | 2004-01-01 22:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
SQL References
SQL Keywords
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE
MySQL Functions
String Functions
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Numeric Functions
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Date Functions
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Advanced Functions
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION
SQL Server Functions
String Functions
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Numeric Functions
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Date Functions
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Advanced Functions
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME
MS Access Functions
String Functions
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Numeric Functions
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Date Functions
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Other Functions
CurrentUser
Environ
IsDate
IsNull
IsNumeric
SQL Quick Ref
DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)
These functions perform date arithmetic. The date is a DATETIME or DATE value specifying the starting date. The expr is an expression specifying the interval value to be added or subtracted from the starting date. The expr is a string; it may start with a ‘-‘ for negative intervals.
A unit is a keyword indicating the units in which the expression should be interpreted.
The INTERVAL keyword and the unit specifier are not case sensitive.
The following table shows the expected form of the expr argument for each unit value.
unit Value | Expected exprFormat |
---|---|
MICROSECOND | MICROSECONDS |
SECOND | SECONDS |
MINUTE | MINUTES |
HOUR | HOURS |
DAY | DAYS |
WEEK | WEEKS |
MONTH | MONTHS |
QUARTER | QUARTERS |
YEAR | YEARS |
SECOND_MICROSECOND | ‘SECONDS.MICROSECONDS’ |
MINUTE_MICROSECOND | ‘MINUTES.MICROSECONDS’ |
MINUTE_SECOND | ‘MINUTES:SECONDS’ |
HOUR_MICROSECOND | ‘HOURS.MICROSECONDS’ |
HOUR_SECOND | ‘HOURS:MINUTES:SECONDS’ |
HOUR_MINUTE | ‘HOURS:MINUTES’ |
DAY_MICROSECOND | ‘DAYS.MICROSECONDS’ |
DAY_SECOND | ‘DAYS HOURS:MINUTES:SECONDS’ |
DAY_MINUTE | ‘DAYS HOURS:MINUTES’ |
DAY_HOUR | ‘DAYS HOURS’ |
YEAR_MONTH | ‘YEARS-MONTHS’ |
The values QUARTER and WEEK are available from the MySQL 5.0.0. version.
mysql> SELECT DATE_ADD('1997-12-31 23:59:59', -> INTERVAL '1:1' MINUTE_SECOND); +---------------------------------------------------------+ | DATE_ADD('1997-12-31 23:59:59', INTERVAL... | +---------------------------------------------------------+ | 1998-01-01 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR); +---------------------------------------------------------+ | DATE_ADD('1999-01-01', INTERVAL 1 HOUR) | +---------------------------------------------------------+ | 1999-01-01 01:00:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
Recommended Reading
Continue your learning on Microsoft SQL Server dates with these tips and
tutorials:
-
Determine SQL Server Date and Time Parts with DATEPART and DATENAME
Functions -
SQL Server Date and Time Data Types
-
SQL Server function to convert integer date to datetime format
-
SQL Database DateTime Best Practices
-
Format SQL Server Dates with FORMAT Function
-
SQL
Server Date Functions -
Add and Subtract Dates using DATEADD in SQL Server
Next Steps
- The formats listed above are not inclusive of all formats provided. Experiment
with the different format numbers to see what others are available. - These formats can be used for all date/time functions, as well as data being
served to clients, so experiment with these data format conversions to see if
they can provide data more efficiently. -
Also, check out the
SQL Server FORMAT Function to Format Dates.
Edgewood Solutions is a technology company focused on Microsoft SQL Server and founder of MSSQLTips.com.
View all my tips
Related Resources
- Date and Time Conversions Using SQL Server…
- Format SQL Server Dates with FORMAT Function…
- Determine SQL Server Date and Time Parts with DATE…
- SQL Server 2008 Date and Time Data Types…
- SQL Server function to convert integer date to dat…
- More Database Developer Tips…
Using DATETIME in SQL
Our New “Users” Table:
id | username | first | last | last_login |
---|---|---|---|---|
1 | ohBillNotAgain | Hillary | Clinton | 2011-12-24 12:59:15 |
2 | internetCreator | Al | Gore | 2011-12-24 11:53:25 |
3 | dontMessWithTexas | George | Bush | 2011-12-24 16:24:17 |
Now, we attempt to get all of our members that logged in before before 1:00PM December 24, 2011.
Example
SELECT * FROM Users WHERE last_login < '2011-12-24 13:00:00'
Result
id | username | first | last | last_login |
---|---|---|---|---|
1 | ohBillNotAgain | Hillary | Clinton | 2011-12-24 12:59:15 |
2 | internetCreator | Al | Gore | 2011-12-24 11:53:25 |
Poor George… Alright, exactly the same syntax as a last one with except we replaced the column name and used a DATETIME string to compare against. The DATETIME data type contains all of the same elements as the DATE data type plus a time string. Commonly referenced as ‘YYYY-MM-DD HH:MM:SS’ Again, in single quotations and with a space separating the date string from the time string, we create our DATE string for comparison. Hillary and Al both make the cut because they logged in before the ‘2011-12-24 13:00:00’ cut off DATETIME. It’s much easier here than it looks in practice. That’s because we put in the DATETIME string by hand. SQL has a few DATE functions you can play around with that you can replace our string with:
Important SQL DATE Functions
Note: SQL DATE functions differ greatly across SQL versions. These are MySQL.
- CURDATE() – gets the current date
- CURTIME() – gets the current time
- NOW() – gets both the date and time (in DATETIME format)
If you are not using MySQL, consider switching. Just kidding, kind of, but no worries, a simple query of Google will help you find the right SQL functions for your SQL database.
SQL Учебник
SQL ГлавнаяSQL ВведениеSQL СинтаксисSQL SELECTSQL SELECT DISTINCTSQL WHERESQL AND, OR, NOTSQL ORDER BYSQL INSERT INTOSQL Значение NullSQL Инструкция UPDATESQL Инструкция DELETESQL SELECT TOPSQL MIN() и MAX()SQL COUNT(), AVG() и …SQL Оператор LIKESQL ПодстановочныйSQL Оператор INSQL Оператор BETWEENSQL ПсевдонимыSQL JOINSQL JOIN ВнутриSQL JOIN СлеваSQL JOIN СправаSQL JOIN ПолноеSQL JOIN СамSQL Оператор UNIONSQL GROUP BYSQL HAVINGSQL Оператор ExistsSQL Операторы Any, AllSQL SELECT INTOSQL INSERT INTO SELECTSQL Инструкция CASESQL Функции NULLSQL ХранимаяSQL Комментарии
STR_TO_DATE(str,format)
This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. The STR_TO_DATE() function returns a DATETIME value if the format string contains both date and time parts. Else, it returns a DATE or TIME value if the string contains only date or time parts.
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y'); +---------------------------------------------------------+ | STR_TO_DATE('04/31/2004', '%m/%d/%Y') | +---------------------------------------------------------+ | 2004-04-31 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, this function returns a Unix timestamp (seconds since ‘1970-01-01 00:00:00’ UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since ‘1970-01-01 00:00:00’ UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD.
mysql> SELECT UNIX_TIMESTAMP(); +---------------------------------------------------------+ | UNIX_TIMESTAMP() | +---------------------------------------------------------+ | 882226357 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00'); +---------------------------------------------------------+ | UNIX_TIMESTAMP('1997-10-04 22:23:00') | +---------------------------------------------------------+ | 875996580 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
SQL Working with Dates
Look at the following table:
Orders Table
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008-11-11 |
2 | Camembert Pierrot | 2008-11-09 |
3 | Mozzarella di Giovanni | 2008-11-11 |
4 | Mascarpone Fabioli | 2008-10-29 |
Now we want to select the records with an OrderDate of «2008-11-11» from the table above.
We use the following statement:
SELECT * FROM Orders WHERE OrderDate=’2008-11-11′
The result-set will look like this:
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008-11-11 |
3 | Mozzarella di Giovanni | 2008-11-11 |
Note: Two dates can easily be compared if there is no time component involved!
Now, assume that the «Orders» table looks like this (notice the
added time-component in the «OrderDate» column):
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008-11-11 13:23:44 |
2 | Camembert Pierrot | 2008-11-09 15:45:21 |
3 | Mozzarella di Giovanni | 2008-11-11 11:12:01 |
4 | Mascarpone Fabioli | 2008-10-29 14:56:59 |
If we use the same statement as above:
SELECT * FROM Orders WHERE OrderDate=’2008-11-11′
we will get no result! This is because the query is looking only for dates with no time portion.
Tip: To keep your queries simple and easy to maintain, do not use time-components in your dates, unless you have to!
❮ Previous
Next ❯
АргументыArguments
format | @ format_varformat | @format_varПорядок следования составляющих частей даты.Is the order of the date parts. Допустимые параметры: mdy, dmy, ymd, ydm, myd и dym.Valid parameters are mdy, dmy, ymd, ydm, myd, and dym. Может быть задано в формате Юникод или в виде двухбайтовой кодировки (DBCS), преобразованной в Юникод.Can be either Unicode or double-byte character sets (DBCS) converted to Unicode. Для языкового стандарта «Английский (США)» значение по умолчанию равно mdy.The U.S. English default is mdy. Значения параметра DATEFORMAT по умолчанию для всех поддерживаемых языков см. в разделе sp_helplanguage (Transact-SQL).For the default DATEFORMAT of all support languages, see sp_helplanguage (Transact-SQL).
Working With SQL Dates
Our “Users” Table:
id | username | first | last | member_since |
---|---|---|---|---|
1 | ohBillNotAgain | Hillary | Clinton | 2011-12-25 |
2 | internetCreator | Al | Gore | 2011-12-8 |
3 | dontMessWithTexas | George | Bush | 2011-7-9 |
Let’s try to get all of our members before December 25, 2011.
Example
SELECT * FROM Users WHERE member_since < '2011-12-25'
Result
id | username | first | last | member_since |
---|---|---|---|---|
2 | internetCreator | Al | Gore | 2011-12-8 |
3 | dontMessWithTexas | George | Bush | 2011-7-9 |
Alright, we said BEFORE December 25, 2011, which means poor Hillary isn’t included because she is on that day. Al barely made the cut, but old George was way before our cut off date. I suppose we should actually talk about what happened. Up to WHERE member_since < ‘2011-12-25’, we know what were doing. We could probably guess what is going on here, but I’ll beat the dead horse. We check our member_since column to see if it is less than, <, our date, which was written in single quotes as ‘2011-12-25’. Often when googling for help with dates, you see this syntax referred to as ‘YYYY-MM-DD’, where Y is for year, M is for month, and D is for day, obviously. Each repetition is a symbol of a blank character space for that element. So, you only want 2 digits for month because that makes sense, and maybe you don’t care about the first 2 characters of year. Instead you just write, YY to get 11. Easy enough, onto the wonderful DATETIMEs
TIMESTAMPADD(unit,interval,datetime_expr)
This function adds the integer expression interval to the date or datetime expression datetime_expr. The unit for interval is given by the unit argument, which should be one of the following values −
- FRAC_SECOND
- SECOND, MINUTE
- HOUR, DAY
- WEEK
- MONTH
- QUARTER or
- YEAR
The unit value may be specified using one of the keywords as shown or with a prefix of SQL_TSI_.
For example, DAY and SQL_TSI_DAY both are legal.
mysql> SELECT TIMESTAMPADD(MINUTE,1,'2003-01-02'); +---------------------------------------------------------+ | TIMESTAMPADD(MINUTE,1,'2003-01-02') | +---------------------------------------------------------+ | 2003-01-02 00:01:00 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
Типы данных Access
Типы данных Access разделяются на следующие группы:
- Текстовый – максимально 255 байтов.
- Мемо — до 64000 байтов.
-
Числовой — 1,2,4 или 8 байтов.Для числового типа размер поля м.б. следующим:
- байт — целые числа от -0 до 255, занимает при хранении 1 байт
- целое — целые числа от -32768 до 32767, занимает 2 байта
- длинное целое — целые числа от -2147483648 до 2147483647, занимает 4 байта
- с плавающей точкой — числа с точностью до 6 знаков от –3,4*1038 до 3,4*1038, занимает 4 байта
- с плавающей точкой — числа с точностью от –1,797*10308 до 1,797*10308, занимает 8 байт
- Дата-время — 8 байтов
- Денежный — 8 байтов, данные о денежных суммах, хранящиеся с 4 знаками после запятой.
- Счетчик — уникальное длинное целое, генерируемое Access при создании каждой новой записи — 4 байта.
- Логический — логические данные 1бит.
- Поле объекта OLE — до 1 гигабайта, картинки, диаграммы и другие объекты OLE из приложений Windows. Объекты OLE могут быть связанными или внедренными.
- Гиперссылки — поле, в котором хранятся гиперссылки. Гиперссылка может быть либо типа UNC (стандартный формат для указания пути с включением сетевого сервера файлов), либо URL(адрес объекта, документа, страницы или объекта другого типа в Интернете или Интранете. Адрес URL определяет протокол для доступа и конечный адрес).
- Мастер подстановок — поле, позволяющее выбрать значение из другой таблицы Accesss или из списка значений, используя поле со списком. Чаще всего используется для ключевых полей. Имеет тот же размер, что и первичный ключ, являющийся также и полем подстановок, обычно 4 байта. (Первичный ключ – одно или несколько полей, комбинация значений которых однозначно определяет каждую запись в таблице Accesss. Не допускает неопределенных .Null. значений, всегда должен иметь уникальный индекс. Служит для связывания таблицы с вторичными ключами других таблиц).
Функции для вычисления разницы между моментами
TIMEDIFF(param1, param2) — возвращает разницу между
значениями времени, заданными параметрами param1 и param2.
DATEDIFF(param1, param2) — возвращает разницу между
датами param1 и param2. Значения param1 и param2 могут иметь типы DATE или DATETIME, а при
вычислении разницы используется лишь часть DATE.
PERIOD_DIFF(param1, param2) — возвращает разницу в месяцах между
датами param1 и param2. Значения param1 и param2 могут быть представлены в числовом формате
YYYYMM или YYMM.
TIMESTAMPDIFF(interval, param1, param2) — возвращает разницу между
значениями датами param1 и param2. Значения param1 и param2 могут быть представлены в форматах
‘YYYY-MM-DD’ или ‘YYYY-MM-DD hh:mm:ss’. Единица измерения разницы задаётся параметром interval. Он может
принимать значения FRAC_SECOND (микросекунды), SECOND (секунды), MINUTE (минуты), HOUR (часы),
DAY (дни), WEEK (недели), MONTH (месяцы), QUARTER (кварталы), YEAR (годы).
PostgreSQL
To get the current date in PostgreSQL, we can use one of several functions:
Function | Returns |
CURRENT_DATE | Current date and time |
CURRENT_TIMESTAMP | Current date and time with timezone |
LOCALTIMESTAMP | Current date and time |
NOW | Current date and time, same as CURRENT_TIMESTAMP |
The return values of these functions look like this:
Results:
Function | Result |
CURRENT_DATE | 2020-07-16 |
CURRENT_TIMESTAMP | 2020-07-16 05:19:32.201578 EDT |
LOCALTIMESTAMP | 2020-07-16 05:19:32 |
NOW | 2020-07-16 05:19:32.201578 EDT |
We can see that CURRENT_DATE shows only the date, but CURRENT_TIMESTAMP and LOCALTIMESTAMP show the date and time.
What’s the Difference Between CURRENT_TIMESTAMP and LOCALTIMESTAMP in PostgreSQL?
The difference is that LOCALTIMESTAMP returns a timestamp without a timezone, and CURRENT_TIMESTAMP returns a timestamp with a timezone.
Пример
Рассмотрим примеры MySQL функции DATE_SUB, чтобы понять, как использовать функцию DATE_SUB в MySQL.
Например:
MySQL
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21.000001’, INTERVAL 4 MICROSECOND);
#Результат: 2014-11-02 08:44:20.999997
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL -20 SECOND);
#Результат: 2014-11-02 08:44:41
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL 25 MINUTE);
#Результат: 2014-11-02 08:19:21
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL 2 HOUR);
#Результат: 2014-11-02 06:44:21
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL 10 DAY);
#Результат: 2014-10-23
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL 12 WEEK);
#Результат: 2014-08-10
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL 3 MONTH);
#Результат: 2014-08-02
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL 3 QUARTER);
#Результат: 2014-02-02
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL 5 YEAR);
#Результат: 2009-11-02
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21.000001’, INTERVAL ‘12.000001’ SECOND_MICROSECOND);
#Результат: 2014-11-02 08:44:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21.000001’, INTERVAL ‘3:12.000001’ MINU
#Результат: 2014-11-02 08:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘3:12’ MINUTE_SECOND);
#Результат: 2014-11-02 08:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21.000001’, INTERVAL ‘1:03:12.000001’ HOUR_MICROSECOND);
#Результат: 2014-11-02 07:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘1:03:12’ HOUR_SECOND);
#Результат: 2014-11-02 07:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘1:03’ HOUR_MINUTE);
#Результат: 2014-11-02 07:41:21
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21.000001’, INTERVAL ‘7 1:03:12.000001’ DAY_MICROSECOND);
#Результат: 2014-10-26 07:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘7 1:03:12’ DAY_SECOND);
#Результат: 2014-10-26 07:41:09
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘7 1:03’ DAY_MINUTE);
#Результат: 2014-10-26 07:41:21
mysql> SELECT DATE_SUB(‘2014-11-02 08:44:21’, INTERVAL ‘7 1’ DAY_HOUR);
#Результат: 2014-10-26 07:44:21
mysql> SELECT DATE_SUB(‘2014-11-02’, INTERVAL ‘5-3’ YEAR_MONTH);
#Результат: 2009-08-02
1 |
mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21.000001’,INTERVAL4MICROSECOND); #Результат: 2014-11-02 08:44:20.999997 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL-20SECOND); #Результат: 2014-11-02 08:44:41 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL25MINUTE); #Результат: 2014-11-02 08:19:21 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL2HOUR); #Результат: 2014-11-02 06:44:21 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL10DAY); #Результат: 2014-10-23 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL12WEEK); #Результат: 2014-08-10 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL3MONTH); #Результат: 2014-08-02 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL3QUARTER); #Результат: 2014-02-02 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL5YEAR); #Результат: 2009-11-02 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21.000001’,INTERVAL’12.000001’SECOND_MICROSECOND); #Результат: 2014-11-02 08:44:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21.000001’,INTERVAL’3:12.000001’MINU #Результат: 2014-11-02 08:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’3:12’MINUTE_SECOND); #Результат: 2014-11-02 08:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21.000001’,INTERVAL’1:03:12.000001’HOUR_MICROSECOND); #Результат: 2014-11-02 07:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’1:03:12’HOUR_SECOND); #Результат: 2014-11-02 07:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’1:03’HOUR_MINUTE); #Результат: 2014-11-02 07:41:21 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21.000001’,INTERVAL’7 1:03:12.000001’DAY_MICROSECOND); #Результат: 2014-10-26 07:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’7 1:03:12’DAY_SECOND); #Результат: 2014-10-26 07:41:09 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’7 1:03’DAY_MINUTE); #Результат: 2014-10-26 07:41:21 mysql>SELECTDATE_SUB(‘2014-11-02 08:44:21’,INTERVAL’7 1’DAY_HOUR); #Результат: 2014-10-26 07:44:21 mysql>SELECTDATE_SUB(‘2014-11-02’,INTERVAL’5-3’YEAR_MONTH); #Результат: 2009-08-02 |
DATE_FORMAT(date,format)
This command formats the date value as per the format string.
The following specifiers may be used in the format string. The ‘%’ character is required before the format specifier characters.
Sr.No. | Specifier & Description |
---|---|
1 |
%a Abbreviated weekday name (Sun..Sat) |
2 |
%b Abbreviated month name (Jan..Dec) |
3 |
%c Month, numeric (0..12) |
4 |
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, .) |
5 |
%d Day of the month, numeric (00..31) |
6 |
%e Day of the month, numeric (0..31) |
7 |
%f Microseconds (000000..999999) |
8 |
%H Hour (00..23) |
9 |
%h Hour (01..12) |
10 |
%I Hour (01..12) |
11 |
%i Minutes, numeric (00..59) |
12 |
%j Day of year (001..366) |
13 |
%k Hour (0..23) |
14 |
%l Hour (1..12) |
15 |
%M Month name (January..December) |
16 |
%m Month, numeric (00..12) |
17 |
%p AM or PM |
18 |
%r Time, 12-hour (hh:mm:ss followed by AM or PM) |
19 |
%S Seconds (00..59) |
20 |
%s Seconds (00..59) |
21 |
%T Time, 24-hour (hh:mm:ss) |
22 |
%U Week (00..53), where Sunday is the first day of the week |
23 |
%u Week (00..53), where Monday is the first day of the week |
24 |
%V Week (01..53), where Sunday is the first day of the week; used with %X |
25 |
%v Week (01..53), where Monday is the first day of the week; used with %x |
26 |
%W Weekday name (Sunday..Saturday) |
27 |
%w Day of the week (0=Sunday..6=Saturday) |
28 |
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V |
29 |
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v |
30 |
%Y Year, numeric, four digits |
31 |
%y Year, numeric (two digits) |
32 |
%% A literal .%. character |
33 |
%x x, for any.x. not listed above |
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y') | +---------------------------------------------------------+ | Saturday October 1997 | +---------------------------------------------------------+ 1 row in set (0.00 sec) mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00' -> '%H %k %I %r %T %S %w'); +---------------------------------------------------------+ | DATE_FORMAT('1997-10-04 22:23:00....... | +---------------------------------------------------------+ | 22 22 10 10:23:00 PM 22:23:00 00 6 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
Функции, характеризующие момент (значение аргумента)
DATE(datetime) — извлекает из значения даты и времени суток
в формате DATETIME (‘YYYY-MM-DD hh:mm:ss’) только дату, отсекая часы, минуты и секунды.
TIME(datetime) — извлекает из значения даты и времени суток
в формате DATETIME (‘YYYY-MM-DD hh:mm:ss’) только время суток, отсекая дату.
TIMESTAMP(param) — принимает в качестве аргумента дату и время
суток в полном или кратком формате и возвращает полный вариант в формате
DATETIME (‘YYYY-MM-DD hh:mm:ss’).
DAY(date), DAYOFMONTH(date) — принимают в качестве аргумента дату,
и возвращают порядковый номер дня в месяце (от 1 до 31).
DAYNAME(date) — принимает в качестве аргумента дату,
и возвращает день недели в виде полного слова на английском языке.
DAYOFWEEK(date) — принимает в качестве аргумента дату,
и возвращает порядкоый номер дня недели от 1 (воскресенье) до 7 (суббота).
WEEKDAY(date) — принимает в качестве аргумента дату,
и возвращает порядкоый номер дня недели от 0 (понедельник) до 6 (воскресенье).
WEEK(date) — принимает в качестве аргумента дату,
и возвращает номер недели в году для этой даты от 0 до 53.
WEEKOFYEAR(datetime) — возвращает порядковый номер недели в году
для даты datetime от 1 до 53.
MONTH(datetime) — возвращает числовое значение месяца года от 1 до 12
для даты datetime.
MONTHNAME(datetime) — возвращает строку с названием месяца
для даты datetime.
QUARTER(datetime) — возвращает значение квартала от 1 до 4
для даты datetime, которая может быть передана в формате ‘YYYY-MM-DD’ или ‘YYYY-MM-DD hh:mm:ss’.
YEAR(datetime) — возвращает год от 1000 до 9999
для даты datetime.
DAYOFYEAR(date) — возвращает порядковый номер дня в году
от 1 до 366 для даты date.
HOUR(datetime) — возвращает значение часа от 0 до 23 для
времени datetime.
MINUTE(datetime) — возвращает значение минут от 0 до 59 для
времени datetime.
SECOND(time) — возвращает количество секунд для времени суток
time, которое задаётся либо в виде строки ‘hh:mm:ss’, либо числа hhmmss.
EXTRACT(type FROM datetime) — принимает дату и время суток datetime
и возвращает часть, определяемую параметром type. Значениями параметра могут быть YEAR, MONTH, DAY,
HOUR, MINUTE, SECOND.
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on a Sunday or a Monday and whether the return value should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the value of the default_week_format system variable is used
Mode | First Day of week | Range | Week 1 is the first week. |
---|---|---|---|
Sunday | 0-53 | with a Sunday in this year | |
1 | Monday | 0-53 | with more than 3 days this year |
2 | Sunday | 1-53 | with a Sunday in this year |
3 | Monday | 1-53 | with more than 3 days this year |
4 | Sunday | 0-53 | with more than 3 days this year |
5 | Monday | 0-53 | with a Monday in this year |
6 | Sunday | 1-53 | with more than 3 days this year |
7 | Monday | 1-53 | with a Monday in this year |
mysql> SELECT WEEK('1998-02-20'); +---------------------------------------------------------+ | WEEK('1998-02-20') | +---------------------------------------------------------+ | 7 | +---------------------------------------------------------+ 1 row in set (0.00 sec)
SQL Справочник
SQL Ключевые слова
ADD
ADD CONSTRAINT
ALTER
ALTER COLUMN
ALTER TABLE
ALL
AND
ANY
AS
ASC
BACKUP DATABASE
BETWEEN
CASE
CHECK
COLUMN
CONSTRAINT
CREATE
CREATE DATABASE
CREATE INDEX
CREATE OR REPLACE VIEW
CREATE TABLE
CREATE PROCEDURE
CREATE UNIQUE INDEX
CREATE VIEW
DATABASE
DEFAULT
DELETE
DESC
DISTINCT
DROP
DROP COLUMN
DROP CONSTRAINT
DROP DATABASE
DROP DEFAULT
DROP INDEX
DROP TABLE
DROP VIEW
EXEC
EXISTS
FOREIGN KEY
FROM
FULL OUTER JOIN
GROUP BY
HAVING
IN
INDEX
INNER JOIN
INSERT INTO
INSERT INTO SELECT
IS NULL
IS NOT NULL
JOIN
LEFT JOIN
LIKE
LIMIT
NOT
NOT NULL
OR
ORDER BY
OUTER JOIN
PRIMARY KEY
PROCEDURE
RIGHT JOIN
ROWNUM
SELECT
SELECT DISTINCT
SELECT INTO
SELECT TOP
SET
TABLE
TOP
TRUNCATE TABLE
UNION
UNION ALL
UNIQUE
UPDATE
VALUES
VIEW
WHERE
MySQL Функции
Функции строк
ASCII
CHAR_LENGTH
CHARACTER_LENGTH
CONCAT
CONCAT_WS
FIELD
FIND_IN_SET
FORMAT
INSERT
INSTR
LCASE
LEFT
LENGTH
LOCATE
LOWER
LPAD
LTRIM
MID
POSITION
REPEAT
REPLACE
REVERSE
RIGHT
RPAD
RTRIM
SPACE
STRCMP
SUBSTR
SUBSTRING
SUBSTRING_INDEX
TRIM
UCASE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATAN2
AVG
CEIL
CEILING
COS
COT
COUNT
DEGREES
DIV
EXP
FLOOR
GREATEST
LEAST
LN
LOG
LOG10
LOG2
MAX
MIN
MOD
PI
POW
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SUM
TAN
TRUNCATE
Функции дат
ADDDATE
ADDTIME
CURDATE
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP
CURTIME
DATE
DATEDIFF
DATE_ADD
DATE_FORMAT
DATE_SUB
DAY
DAYNAME
DAYOFMONTH
DAYOFWEEK
DAYOFYEAR
EXTRACT
FROM_DAYS
HOUR
LAST_DAY
LOCALTIME
LOCALTIMESTAMP
MAKEDATE
MAKETIME
MICROSECOND
MINUTE
MONTH
MONTHNAME
NOW
PERIOD_ADD
PERIOD_DIFF
QUARTER
SECOND
SEC_TO_TIME
STR_TO_DATE
SUBDATE
SUBTIME
SYSDATE
TIME
TIME_FORMAT
TIME_TO_SEC
TIMEDIFF
TIMESTAMP
TO_DAYS
WEEK
WEEKDAY
WEEKOFYEAR
YEAR
YEARWEEK
Функции расширений
BIN
BINARY
CASE
CAST
COALESCE
CONNECTION_ID
CONV
CONVERT
CURRENT_USER
DATABASE
IF
IFNULL
ISNULL
LAST_INSERT_ID
NULLIF
SESSION_USER
SYSTEM_USER
USER
VERSION
SQL Server функции
Функции строк
ASCII
CHAR
CHARINDEX
CONCAT
Concat with +
CONCAT_WS
DATALENGTH
DIFFERENCE
FORMAT
LEFT
LEN
LOWER
LTRIM
NCHAR
PATINDEX
QUOTENAME
REPLACE
REPLICATE
REVERSE
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
TRANSLATE
TRIM
UNICODE
UPPER
Функции чисел
ABS
ACOS
ASIN
ATAN
ATN2
AVG
CEILING
COUNT
COS
COT
DEGREES
EXP
FLOOR
LOG
LOG10
MAX
MIN
PI
POWER
RADIANS
RAND
ROUND
SIGN
SIN
SQRT
SQUARE
SUM
TAN
Функции дат
CURRENT_TIMESTAMP
DATEADD
DATEDIFF
DATEFROMPARTS
DATENAME
DATEPART
DAY
GETDATE
GETUTCDATE
ISDATE
MONTH
SYSDATETIME
YEAR
Функции расширений
CAST
COALESCE
CONVERT
CURRENT_USER
IIF
ISNULL
ISNUMERIC
NULLIF
SESSION_USER
SESSIONPROPERTY
SYSTEM_USER
USER_NAME
MS Access функции
Функции строк
Asc
Chr
Concat with &
CurDir
Format
InStr
InstrRev
LCase
Left
Len
LTrim
Mid
Replace
Right
RTrim
Space
Split
Str
StrComp
StrConv
StrReverse
Trim
UCase
Функции чисел
Abs
Atn
Avg
Cos
Count
Exp
Fix
Format
Int
Max
Min
Randomize
Rnd
Round
Sgn
Sqr
Sum
Val
Функции дат
Date
DateAdd
DateDiff
DatePart
DateSerial
DateValue
Day
Format
Hour
Minute
Month
MonthName
Now
Second
Time
TimeSerial
TimeValue
Weekday
WeekdayName
Year
Другие функции
CurrentUser
Environ
IsDate
IsNull
IsNumeric
SQL ОператорыSQL Типы данныхSQL Краткий справочник