SQL Server gets all the records of the previous day
This article describes how to query all records of the previous day in a table containing a datetime column in SQL Server. The following SQL statements apply to SQL Server 2005 and later:
<code class="language-sql">SELECT * FROM YourTable WHERE YourDate >= DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0) AND YourDate < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)</code>
This statement selects records from the YourTable
table where the YourDate
column is greater than or equal to midnight of the previous day and less than midnight of the current day.
Explanation of statement:
DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0)
: This expression returns the start time of the previous day (midnight). DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
: This expression returns the start time of the day (midnight). Filter by this condition to ensure that only records from the previous day are obtained, excluding records from the current day and earlier dates.
The above is the detailed content of How to Select All Rows from the Previous Day Using SQL Server?. For more information, please follow other related articles on the PHP Chinese website!