DATEDIFF Getting the previous month
You can use DATEADD
eg.
SELECT DATEADD(month, -1, GETDATE())
Get the records of last month in SQL server
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
You need to check the month and year.
SQL get previous month (in January too)
Try This
select CASE WHEN month(getdate())>1 THEN month(getdate())-1 ELSE 12 END ,
CASE WHEN month(getdate())>1 THEN YEAR (getdate()) ELSE YEAR (getdate()) -1 END
Get the previous month number including year
Try with case when like below:
UPDATE Company_Coupon
SET Total_Coupons = @count
WHERE CompanyID = 1205
AND Month = (case when MONTH(GETDATE())-1=0 then 12 else MONTH(GETDATE())-1 end) AND Year = (case when MONTH(GETDATE())-1=0 then YEAR (GETDATE())-1 else YEAR (GETDATE()) end)
How is this SQL function getting the first day of the previous month?
Rewriting it like this:
DATEADD(month, DATEDIFF(month, '20100101', getdate()) - 1, '20100101')
probably makes it clearer.
There's some dodgy and obscure stuff going on.
This
DATEDIFF(month, -1, getdate())
counts the month boundaries crossed between two dates, the first one is
cast(-1 as datetime) --1899-12-31 00:00:00.000
Then it subtracts 2 from that and add that many months to
cast(0 as datetime) --1900-01-01 00:00:00.000
Most optimal way to get all records IN previous month
Your query is slow because when you do DATEDIFF(m, [DATE_COL], GETDATE())
it can not use any indexes on the [Date_Col]
.
Anyway you can use the following where clause, this will use indexes on the [SettlementDate]
and hopefully it should perform a lot better than the DATEDIFF()
function.
WHERE [SettlementDate] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND [SettlementDate] < DATEADD(DAY,1,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1))
Related Topics
Finding the Highest Average Salary in SQL
Insert Value into Table If Conidition Is Met At Least One Time
What's the Best Way to Capitalise the First Letter of Each Word in a String in SQL Server
Multiplying Two Columns in SQL Server
How to Directly View Blobs in MySQL Workbench
How to Select an Empty Result Set
Access Denied for Load Data Infile in MySQL
Add a Column to Specific Position in Mssql Server
Simple Check for Select Query Empty Result
Query to Calculate Average of Employee Salaries Working Under Manager in SQL
Node.Js Mssql Tedius Connectionerror: Failed to Connect to Localhost:1433 - Connect Econnrefused
How to Replace Single-Quote With Double-Quote in SQL Query - Oracle 10G
What Is the Best Datatype for Storing Urls in a MySQL Database
Sql Select Radius Search Based on Latitude Longitude
Comparing Two Count Results Using SQL
How to Find Multiple Occurrence of Particular String and Fetch Value in SQL Server
Delete Rows With Date Older Than 30 Days With SQL Server Query