简体   繁体   中英

Get date of 3 days ago

I have SQL script that selects everything from current day.

SELECT  [ClientID] from [logs] where Date > CONVERT (date, SYSDATETIME())

Date is type of DateTime.

How to get everything within last 3 days? I suppose I need subtract 3 days from function SYSDATETIME() result, but how?

SELECT  [ClientID] from [logs] where Date > DATEADD(day, -3, CONVERT (date, SYSDATETIME()))

Use GETDATE() : Yes, it gets date from system!

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

Query:

SELECT  [ClientID] from [logs] where ( Date  > GETDATE() - 3)

More Reference:

GETDATE Detailed Documentation

对于mysql使用此:

SELECT DATE_ADD(CURRENT_DATE, INTERVAL - 3 DAY);

Use BETWEEN

SELECT ClientID 
FROM logs
WHERE Date BETWEEN SYSDATETIME() AND SYSDATETIME() - 3

Using BETWEEN is nice. I also prefer the DATEADD function. But be aware of the fact that the SYSDATETIME function (or I would us GETDATE()) also includes the time which would mean that events before the current time but within the three day period may not be included. You may have to convert both sides to a date instead of datetime.

SELECT  [ClientID] from [logs] where Date > DATEADD(day, -3, SYSDATETIME())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM