SQL get previous month (in January too) - sql

Hello I'm looking for simple way, how to get data from previous month. I get this code but it didn't work in January (result is 12 2021 and I need 12 2020)
select month(dateadd(month,-1,getdate())), year(getdate())

Presumably, you have some sort of date column.
In SQL Server, you can express this concept using datediff():
where datediff(month, datecol, getdate()) = 1
However, that is not "sargable", meaning that it prevents the use of indexes. So, I would instead recommend:
where datecol < datefromparts(year(getdate()), month(getdate()), 1) and
datecol >= dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))
If you simply want the first day of the previous month, you can use:
dateadd(month, 1, datefromparts(year(getdate()), month(getdate()), 1))

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

Using the answer given here: How can I select the first day of a month in SQL?
SELECT dateadd(month,-1,DATEADD(month, DATEDIFF(month, 0, getdate()), 0)) as previousmonth;
output:
2020-12-01 00:00:00.000

I can provide next query using FORMAT function:
SELECT
-- get current day in previous month
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-dd') as current_previousmonth,
-- get first of previous month
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM-01') as first_previousmonth,
-- previous month without date
FORMAT(dateadd(month, -1, getdate()), 'yyyy-MM') as previousmonth;
test T-SQL here

Here you go!
select dateadd(mm,-1,eomonth(getdate())) as [Previous Month]
Result:
Previous Month
--------------
2020-12-31
You could also use CONVERT() or FORMAT() functions to format the date as you desire.

Try
SELECT FORMAT(DATEADD(month, -1, GETDATE()),'MM/yyyy');
It will give you previous month and the year. If you are comparing to a date column in a existing table, then you need the date part too as you want to know December of which year was the previous month. But if you don't want the year, then just adjust the 'MM/yyyy' part to suit your purpose.

Related

Getting all data from last month

I am building an SQL view which shows me all entries of table T where the information is last month. I want it so that if I run the view any time in August, it will show me all entries for July, not just a month before which is what I have done with my current code.
Please see this:
where cast(t.Ticket_OpenDate as date) >= cast(dateadd(month, -1, getdate()) as date)
I look forward to hearing from someone.
Using DATEDIFF as in the other answer will not perform well because it cannot use indexes (it is not sarge-able).
It is much better to use a date interval (start and end), in this case we want a half-open interval (exclusive end date):
WHERE t.Ticket_OpenDate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) - 1, 1)
AND t.Ticket_OpenDate < DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()) , 1)
You should be able to use the DATEDIFF() function for that:
WHERE DATEDIFF(month, CAST(t.Ticket_OpenDate as date), GETDATE()) = 1
See db<>fiddle for an example.

Query select where date between "1st day of current month" and "current day"

I need to select data from SQL Server database between the 1st day of the current month and current day.
SELECT *
FROM table_name
WHERE date BETWEEN "1st day of current month" AND "current day"
You can make use of EOMONTH() to jump to the last day of the month, of the previous month. Then, just add 1 day, by using DATEADD() with 1 as the increment for the day, to get the 1st day of the current month.
SELECT *
FROM <table>
WHERE <date> BETWEEN DATEADD(DAY, 1, EOMONTH(GETDATE(), -1)) and GETDATE()
I think this should work,
SELECT *
FROM TABLE_NAME
WHERE date BETWEEN DATEADD(mm, DATEDIFF(mm,0,date), 0) AND GETDATE()
May this will help you,
select * from TABLE_NAME
where date between
dateadd (DAY, -(datepart (DAY, getdate ())) + 1, convert (date, GETDATE ()))
and
convert (date, getdate ())
I don't recommend using between for this purpose. I prefer to have code that works on both dates and datetimes without modification.
In addition, SQL Server has the convenient datefromparts() function. So, I recomend:
WHERE date >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AND
date < CONVERT(DATE, DATEADD(DAY, 1, GETDATE()))

SELECT previous year up to current date

I have a table which has a Start Date column for example:
Start Date
2015/01/05
2015/02/08
2016/01/10
2017/02/10
etc...
I am trying to put into my WHERE clause to select all records where it is one year prior based on the current GETDATE().
For example, if today is July 2019 and I run the query, I'd like for it to run and give me Start Dates starting from July of 2018 up until June of 2019. And if I run it for August of 2019, I'd like for it to show Start Dates from August of 2018 up until July of 2019, and so on. Basically up until the month before of the current date.
Currently I have this in my WHERE clause:
WHERE start_date between DATEADD(YEAR,-1, GETDATE()) and GETDATE()
but this appears I believe to get just one year prior up until the current date exact.
Is there a better way for me to do this?
I think that this is your requirement:
WHERE start_date BETWEEN
DATEFROMPARTS(YEAR(GETDATE()) - 1, MONTH(GETDATE()), 1)
AND
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), -1)
With:
DATEFROMPARTS(YEAR(GETDATE()) - 1, MONTH(GETDATE()), 1)
you get the 1st day of current month in last year.
With:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), -1)
you get the last Day of previous month.
See the demo.
You can use datefromparts() in SQL Server:
where start_date >= datefromparts(year(getdate()) - 1, 1, 1) and
start_date < datefromparts(year(getdate() - 1, month(getdate()), day(getdate())

SQL 15th of the month for Next Year

SQL query to get the 15 of the month for the following year.
Today
select getdate() = 2017-08-23 17:05:24.143
Looking for: 2018-8-15 00:00:00
I know how to get a year from today:
select dateadd(year,1,datediff(day,0,getdate()))
I know how to get the beginning of the month:
SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
However I am having trouble combining the two.
You can use datefromparts for SQL Server versions 2012 and above.
select datefromparts(year(getdate())+1,month(getdate()),15)
Truncate the current day to the start of the month with the code you have, but add 12 months (so, a year), and add 14 days.
select dateadd(day,14,dateadd(month, 12+datediff(month, 0, getdate()), 0))
SELECT DATEADD(month, DATEDIFF(month, 0, DATEADD(year, 1, DATEDIFF(day, 0, GETDATE())), 0)
Vamsi Prabhala's answer deserves to be accepted.
But, you should consider creating a Calendar Table because it greatly simplifies working with dates in general.
Here is a pretty simply query that yields the results that you want:
select * from Calendar C where C.year = datepart(year, getdate()) + 1
and C.day_of_month = 15 and C.month = datepart(m, getdate())
Rextester Demo

How do I calculate the last day of the month in SQL?

Specifically MSSQL 2005.
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
To understand how it works we have to look at the dateadd() and datediff() functions.
DATEADD(datepart, number, date)
DATEDIFF(datepart, startdate, enddate)
If you run just the most inner call to datediff(), you get the current month number since timestamp 0.
select datediff(m, 0, getdate() );
1327
The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.
select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000
Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000
This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.
Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.
dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')
Explanation:
General approach: use temporal functionality.
SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'
These are DATETIME literals, being the first time granule on the first day and last day respectively of the same 31-day month. Which month is chosen is entirely arbitrary.
SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)
This is the difference in whole months between the first day of the reference month and the current timestamp. Let's call this #calc.
SELECT DATEADD(M, #calc, '1990-01-31T00:00:00.000')
This adds #calc month granules to the last day of the reference month, the result of which is the current timestamp 'rounded' to the last day of its month. Q.E. D.
Try this:
DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
They key points are if you can get first day of current month,Last Day of Last Month and Last Day of Current Month.
Below is the Step by Step way to write query:
In SQL Server Date Starts from 1901/01/01( Date 0) and up to now each month can be identified by a number. Month 12 is first month of 1902 means January. Month 1200 is January of 2001. Similarly each day can be assigned by unique number e.g Date 0 is 1901/01/01. Date 31 is 1901/02/01 as January of 1901 starts from 0.
To find out First day of Current Month(Current Date or a given date)
First we need to check how many months have passed since date 0(1901/01/01).
SELECT DATEDIFF(MM,0,GETDATE())
Add same number of month to date 0(1901/01/01)
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0)
Then we will get first day of current month(Current Date or a given date)
To get Last Day of Last Month
We need to subtract a second from first day of current month
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0))
To get Last Day of Current Month
To get first day of current month first we checked how many months have been passed since date 0(1901/01/01). If we add another month with the total months since date 0 and then add total months with date 0, we will get first day of next month.
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0)
If we get first day of next month then to get last day of current month, all we need to subtract a second.
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0))
Hope that would help.
Using SQL2005, you do not have access to a helpful function EOMONTH(), So you must calculate this yourself.
This simple function will works similar to EOMONTH
CREATE FUNCTION dbo.endofmonth(#date DATETIME= NULL)
RETURNS DATETIME
BEGIN
RETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(#date,GETDATE())), ISNULL(#date,GETDATE()))))
END
Query to perform:
SELECT dbo.endofmonth(DEFAULT) --Current month-end date
SELECT dbo.endofmonth('02/25/2012') --User-defined month-end date
Some links to possible answers:
http://www.extremeexperts.com/sql/Tips/DateTrick.aspx
http://www.devx.com/tips/Tip/14405
http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html
DECLARE
#Now datetime,
#Today datetime,
#ThisMonth datetime,
#NextMonth datetime,
#LastDayThisMonth datetime
SET #Now = getdate()
SET #Today = DateAdd(dd, DateDiff(dd, 0, #Now), 0)
SET #ThisMonth = DateAdd(mm, DateDiff(mm, 0, #Now), 0)
SET #NextMonth = DateAdd(mm, 1, #ThisMonth)
SET #LastDayThisMonth = DateAdd(dd, -1, #NextMonth)
Sometimes you really do need the last day of this month, but frequently what you really want is to describe the time interval of this month. This is the best way to describe the time interval of this month:
WHERE #ThisMonth <= someDate and someDate < #NextMonth
For completeness, in Oracle you'd do something like ...
select add_months(trunc(sysdate,'MM'),1) ...
or
select last_day(sysdate)+1 ...
DATEADD(dd, -1, DATEADD(mm, +1, DATEADD(dd, 1 - DATEPART(dd, #myDate), #myDate)))