Get yesterdays date and if Monday get weekend range for SQL server - sql

How do I get yesterdays date and if the current date is Monday I would need Sunday, Saturday and Friday. This is already asked here for ms access. I now need this for SQL server. How would I go about this?
Will create an inline view that will return the previous date in SQL It will return between 1 and 3 rows depending on the current date.
If current date is Monday Return:
Sundays date
Saturdays date
Fridays date
If current date is Tuesday then Return: Mondays date
If current date is Wednesday then Return: Tuesdays date
If current date is Thursday then Return: Wednesdays date
If current date is Friday then Return: Thursdays date
If current date is Saturday then Return: Fridays date
If current date is Sunday then Return: Saturdays date
I hope this helps explain what I am trying to do more clearly.
sample select query
--get previous date
select * from [Purchase Orders] where MyDate in (previous date(s))

Not entirely clear about the question though. But you can do something on the similar lines.
Using DATEPART and DATEADD
DECLARE #TodaysDate DATETIME
SET #TodaysDate = '2013-04-10'
SELECT CASE
WHEN DATEPART (DW, DATEADD (DD, -1, #TodaysDate )) IN (1, 6, 7)
THEN 'WeekEnd' ELSE 'WeekDay'
END D

Using the query you linked to, you can try the code below:
SELECT *
FROM [Purchase Order]
WHERE MyDate >= CASE
WHEN DATENAME(dw, CONVERT(CHAR(8), GETDATE() , 112)) LIKE 'Monday' THEN CONVERT(CHAR(8), DATEADD(dd, -3, GETDATE()), 112)
ELSE CONVERT(CHAR(8), DATEADD(dd, -1, GETDATE()), 112)
END
AND MyDate < CONVERT(CHAR(8),GETDATE(),112)

You can use the following table function:
CREATE FUNCTION dbo.ufnPreviousDay (#suppliedDate DATE)
RETURNS #PreviousDates TABLE (PreviousDate DATE)
AS
BEGIN
INSERT INTO #PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -1, #suppliedDate)
IF DATEPART(WEEKDAY, DATEADD(DAY, ##DATEFIRST - 1, #suppliedDate)) = 1 -- If Monday
BEGIN
INSERT INTO #PreviousDates (
PreviousDate)
SELECT
PreviousDate = DATEADD(DAY, -2, #suppliedDate)
UNION ALL
SELECT
PreviousDate = DATEADD(DAY, -3, #suppliedDate)
END
RETURN
END
You can use it like this:
SELECT
T.*
FROM
dbo.ufnPreviousDay('2018-03-19') AS T
/*
Result:
2018-03-18
2018-03-17
2018-03-16
*/
If you want today's previous dates:
SELECT
T.*
FROM
YourTable AS T
INNER JOIN dbo.ufnPreviousDay(GETDATE()) AS M ON T.MyDate = M.PreviousDate

Related

How to get max Saturday dates in a column of each month, without hardcoding

How to get max Saturday dates in a column of each month in SQL Server. Can someone please help me.
Now I need only the dates which has last Saturday of month.
For example,
The table has
07-08-2021 - Saturday
14-08-2021 - Saturday
21-08-2021 - Saturday
28-08-2021 - Saturday
04-09-2021 - Saturday
11-09-2021 - Saturday
18-09-2021 - Saturday
25-09-2021 - Saturday
Suppose we are in August month, I need to select last Saturday of that month( ONLY 28-08-2021)
Suppose we are in September month, I need to select last Saturday of that month( ONLY 25-09-2021)
Output:
28-08-2021
25-09-2021
assuming you have a datefield in your table (I will refer to it here as such in the below query)
with week as (
select
date_trunc('week', datefield + interval '2 day') - interval '2 day' as week_date
-- ^this adjusts the week date_trunc to start on Saturday (it starts on Monday by default)
from sometable
)
select
extract(month from week_date) as month_num,
max(week_date) as last_saturday
from week
group by month_num
note: if you only have partial data for the current month, this query will need to be altered slightly, but you didn't give me a lot to go off of here
A CTE is defined to populate the day name of entire month and then the requirement is filtered.
;with GetDates As (
select CAST('01-01-2021' as date) as StartDate, datename(dw, '09-01-2021') as Day_Name
UNION ALL
select DATEADD(day,1, StartDate), datename(dw, DATEADD(day,1, StartDate))
from GetDates
where StartDate < '09-30-2021'
)
select max(StartDate)
from GetDates where Day_Name = 'Saturday'
group by month(StartDate)
OPTION (MAXRECURSION 500)
Here is a function to calculate the Nth Weekday - which can calculate from the beginning of the month or from the end of the month.
Alter Function dbo.fnGetNthWeekDay (
#theDate datetime
, #theWeekday int
, #theNthDay int
)
Returns Table
As
Return
/*
Adapted from a version published by Peter Larrson - with minor modifications for performance
and restructured to eliminate usage of a derived table.
Inputs:
#theDate any date in the month
#theWeekday the weekday to calculate: 1 = Monday
2 = Tuesday
3 = Wednesday
4 = Thursday
5 = Friday
6 = Saturday
7 = Sunday
#theNthDay the week count where positive is from beginning of the month
and negative is from end of month
Outputs:
#theDate the date entered
#theNthDate the Nth date of the month
*/
Select theDate = #theDate
, dt.nthDate
From (Values (dateadd(month, datediff(month, #theNthDay, #theDate), 0))) As mm(FirstOfMonth)
Cross Apply (Values (dateadd(day, 7 * #theNthDay - 7 * sign(#theNthDay + 1)
+ (#theWeekday + 6 - datediff(day, -53690, mm.FirstOfMonth) % 7) % 7, mm.FirstOfMonth))) As dt(nthDate)
Where #theWeekday Between 1 And 7
And datediff(month, dt.nthDate, #theDate) = 0
And #theNthDay In (-5, -4, -3, -2, -1, 1, 2, 3, 4, 5);
Go
You can then call it like this:
Select * From dbo.fnGetNthWeekDay('2021-08-15', 6, -1) nwd

reporting Wednesday to wednesday

I am trying run a report based on a Wednesday to Wednesday reporting week.
I have found lots of examples that say the get correct date, such as:
DATEADD(DAY, -5, DATEADD(WEEK, DATEDIFF(WEEK, 0, getdate()), 0))
The problem is that these seem to only work for the current week. The example above gives 15/11/17 which is correct for today (24/11/2017) but incorrect on Sunday (26/11/2017) when it would get the 22/11/2017.
if I look at the report between 22-28/11/2017(Wed-Tue) I should see a report from 15-22/11/2017
Between the 29/11 & 5/12/2017 the report should be from 22-29/11/2017
any help is appreciated!
Try this method
SELECT
*,
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-2,[wensday]) ELSE DATEADD(WEEK,-1,[wensday]) END [from date],
CASE WHEN [wensday]>reportDate THEN DATEADD(WEEK,-1,[wensday]) ELSE [wensday] END [to date]
FROM
(
SELECT
reportDate,
-- monday of this week
--DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0) [monday],
-- wensday of this week
DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,reportDate)/7*7,0)) [wensday]
FROM
(
SELECT CAST('20171115' AS date) reportDate
UNION ALL
SELECT CAST('20171121' AS date) reportDate
UNION ALL
SELECT CAST('20171122' AS date) reportDate
UNION ALL
SELECT CAST('20171123' AS date) reportDate
UNION ALL
SELECT CAST('20171124' AS date) reportDate
UNION ALL
SELECT CAST('20171129' AS date) reportDate
UNION ALL
SELECT CAST('20171205' AS date) reportDate
) test
) q
The inline algorithm
DECLARE #reportDate date=GETDATE()
DECLARE #Wensday date=DATEADD(DAY,2,DATEADD(DAY,DATEDIFF(DAY,0,#reportDate)/7*7,0))
DECLARE #FromDate date=CASE WHEN #Wensday>#reportDate THEN DATEADD(WEEK,-2,#Wensday) ELSE DATEADD(WEEK,-1,#Wensday) END
DECLARE #ToDate date=DATEADD(WEEK,1,#FromDate)
SELECT #reportDate,#Wensday,#FromDate,#ToDate
You can use DATEFIRST to assign days 1-7 to Wed - Tue
Whatever date you put in here, it will return the first prior Wednesday
The following Tuesday is just 6 days after that.
-- Wednesday will be 1 when we use datepart dw
SET DATEFIRST 3;
DECLARE #ReportDate DATE
SET #ReportDate = '2017-11-26'
SELECT
DATEADD( d,
-(DATEPART(dw,#ReportDate)-1),
#ReportDate
)
Try this...
DECLARE #fDt as date,#fDtR as date
set #fDt = '11/15/2017'
SET DATEFIRST 3
SELECT #fDtR = DATEADD(d,-6-(DATEPART(dw,#fDt)),#fDt)
print #fDtR
you can try this
select * from youtablename where yourdatefield <=
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0)) and yourdatefield >
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
From this you will get last wednesday
select
dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,0))
and from this you will get last to last wednesday
select dateadd(dd,datediff(dd,0,getdate())/7 * 7 + 2,-7))
so that you can find Wednesday to Wednesday data.

tsql: How to retrieve the last date of each month between given date range

I have two date for example 08/08/2013 and 11/11/2013 and I need last date of each month starting from August to November in a table so that i can iterate over the table to pick those dates individually.
I know how to pick last date for any month but i am stucked with a date range.
kindly help, it will be highly appreciated.
Note : I am using Sql 2008 and date rang could be 1 month , 2 month or 6 month or a year or max too..
You can use CTE for getting all last days of the month within the defined range
Declare #Start datetime
Declare #End datetime
Select #Start = '20130808'
Select #End = '20131111'
;With CTE as
(
Select #Start as Date,Case When DatePart(mm,#Start)<>DatePart(mm,#Start+1) then 1 else 0 end as [Last]
UNION ALL
Select Date+1,Case When DatePart(mm,Date+1)<>DatePart(mm,Date+2) then 1 else 0 end from CTE
Where Date<#End
)
Select * from CTE
where [Last]=1 OPTION ( MAXRECURSION 0 )
DECLARE #tmpTable table (LastDates DATE);
DECLARE #startDate DATE = '01/01/2012'; --1 Jan 2012
DECLARE #endDate DATE = '05/31/2012'; --31 May 2012
DECLARE #tmpEndDate DATE;
SET #startDate = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#startDate)+1,1));
SET #tmpEndDate = DATEADD(DAY, 1, #endDate);
WHILE (#startDate <= #tmpEndDate)
BEGIN
INSERT INTO #tmpTable (LastDates) values (DATEADD(DAY, -1, #startDate));
SET #startDate = DATEADD(MONTH, 1, #startDate);
END
SELECT [LastDates] FROM #tmpTable;
Output:
Example: 1
#startDate DATE = '01/01/2012'; --1 Jan 2012
#endDate DATE = '05/31/2012'; --31 May 2012
LastDates
----------
2012-01-31
2012-02-29
2012-03-31
2012-04-30
2012-05-31
Example: 2
#startDate DATE = '11/01/2011'; --1 Nov 2011
#endDate DATE = '03/13/2012'; --13 Mar 2012
LastDates
----------
2011-11-30
2011-12-31
2012-01-31
2012-02-29
I've created a table variable, filled it with all days between #startDate and #endDate and searched for max date in the month.
declare #tmpTable table (dates date)
declare #startDate date = '08/08/2013'
declare #endDate date = '11/11/2013'
while #startDate <= #endDate
begin
insert into #tmpTable (dates) values (#startDate)
set #startDate = DATEADD(DAY, 1, #startDate)
end
select max(dates) as [Last day] from #tmpTable as o
group by datepart(YEAR, dates), datepart(MONTH, dates)
Results:
Last day
2013-08-31
2013-09-30
2013-10-31
2013-11-11
To also get last day of November this can be used before loop:
set #endDate = DATEADD(day, -1, DATEADD(month, DATEDIFF(month, 0, #endDate) + 1, 0))
Following script demonstrates the script to find last day of previous, current and next month.
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
If you want to find last day of month of any day specified use following script.
--Last Day of Any Month and Year
DECLARE #dtDate DATETIME
SET #dtDate = '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#dtDate)+1,0))
LastDay_AnyMonth
ResultSet:
LastDay_AnyMonth
Source - SQL Server Central.
You can use a recursive CTE to do this, note the MAXRECURSION OPTION prevents an infinite loop:
DECLARE #StartDate DATE = '2013-08-08'
DECLARE #EndDate DATE = '2013-11-11'
;WITH dateCTE
AS
(
SELECT CAST(DATEADD(M, 1,DATEADD(d, DAY(#StartDate) * -1, #StartDate)) AS DATE) EndOFMonth
UNION ALL
SELECT CAST(DATEADD(M, 2,DATEADD(d, DAY(EndOFMonth) * -1, EndOFMonth)) AS DATE)
FROM dateCTE
WHERE EndOFMonth < DATEADD(d, DAY(#EndDate) * -1, #EndDate)
)
SELECT *
FROM dateCTE
OPTION (MAXRECURSION 30);
This returns
EndOFMonth
----------
2013-08-31
2013-09-30
2013-10-31
try this
the last row(where) is optional for date filtering
declare #table table
(
thisdate date
)
insert into #table values ('12/01/2013'),('05/06/2013'),('04/29/2013'),('02/20/2013')
select *,DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,thisdate)+1,0))
LastDay from #table
where thisdate between 'givendate' and 'givendate'
The Example Below is for all dates
thisdate lastday
2013-12-01 2013-12-31 23:59:59.000
2013-05-06 2013-05-31 23:59:59.000
2013-04-29 2013-04-30 23:59:59.000
2013-02-20 2013-02-28 23:59:59.000
The following CTE gives you the last day of every month from February 1900 until the middle of the 26th century (on my machine):
;with LastDaysOfMonths as (
select DATEADD(month,
ROW_NUMBER() OVER (ORDER BY so.object_id),
'19000131') as Dt
from sys.objects so,sys.objects so1
)
select * from LastDaysOfMonths
It should be easy enough to use it as part of a larger query or to filter it down to just the dates you want. You can adjust the range of years as needed by changing the constant 19000131. The only important thing to do is make sure that you use a month that has 31 days in it and always have the constant be for day 31.
No need to use a common table expression or anything like that - this simple query will do it:
SELECT DATEADD(d, -1, DATEADD(mm, DATEDIFF(m, 0, DATEADD(m, number, '2013-08-08')) + 1, 0)) AS EndOfMonth
FROM master.dbo.spt_values
WHERE 'P' = type
AND DATEADD(m, number, '2013-08-08') < '2013-11-11';
Although the question is about the last day which #bummi has already answered.
But here is the solution for the first date which might be helpful for someone.
Get the first dates of all the months in-between the #FromDate and #ToDate.
DECLARE #FromDate DATETIME = '2019-08-13'
DECLARE #ToDate DATETIME = '2019-11-25'
;WITH CTE
AS
(
SELECT DATEADD(DAY, -(DAY(#FromDate) - 1), #FromDate) AS FirstDateOfMonth
UNION ALL
SELECT DATEADD(MONTH, 1, FirstDateOfMonth)
FROM CTE
WHERE FirstDateOfMonth < DATEADD(DAY, -(DAY(#ToDate) - 1), #ToDate)
)
SELECT * FROM CTE
Here is the result
--Result
2019-08-01 00:00:00.000
2019-09-01 00:00:00.000
2019-10-01 00:00:00.000
2019-11-01 00:00:00.000

Select rows with date field having values within this week

I am trying to select all the rows from a table where a date field has values within the current week. I want the rows from the current week's Monday until the current day.
Example:
ID adate
---------------
1 11-11-2010
2 12-11-2010
3 13-11-2010
4 14-11-2010
5 15-11-2010
The rows I want in this case are:
ID adate
---------------
4 14-11-2010 //this week's Monday
5 15-11-2010 //till today
This will work on a week from Sunday to Saturday. You shall adapt it if you want weeks from Monday to Sunday:
select *
from myTable
where aDate between
cast('now' as date) - extract(weekday from cast('now' as date)) --prev sunday
and
cast('now' as date) - extract(weekday from cast('now' as date)) + 6 --next saturday
;
I wrote it in ms sql:
declare #today as datetime
declare #first_day_of_week datetime
set #today = convert(varchar, getDate(), 101)
set #first_day_of_week = dateadd(day, -(DATEPART(WEEKDAY, #today) - 1), #today)
select *
from [table]
where adate between #first_day_of_week and #today
Sunday is the beginning of the week.

Get the last day of the month in SQL

I need to get the last day of the month given as a date in SQL. If I have the first day of the month, I can do something like this:
DATEADD(DAY, DATEADD(MONTH,'2009-05-01',1), -1)
But does anyone know how to generalize it so I can find the last day of the month for any given date?
From SQL Server 2012 you can use the EOMONTH function.
Returns the last day of the month that contains the specified date,
with an optional offset.
Syntax
EOMONTH ( start_date [, month_to_add ] )
How ... I can find the last day of the month for any given date?
SELECT EOMONTH(#SomeGivenDate)
Here's my version. No string manipulation or casting required, just one call each to the DATEADD, YEAR and MONTH functions:
DECLARE #test DATETIME
SET #test = GETDATE() -- or any other date
SELECT DATEADD(month, ((YEAR(#test) - 1900) * 12) + MONTH(#test), -1)
You could get the days in the date by using the DAY() function:
dateadd(day, -1, dateadd(month, 1, dateadd(day, 1 - day(date), date)))
Works in SQL server
Declare #GivenDate datetime
SET #GivenDate = GETDATE()
Select DATEADD(MM,DATEDIFF(MM, 0, #GivenDate),0) --First day of the month
Select DATEADD(MM,DATEDIFF(MM, -1, #GivenDate),-1) --Last day of the month
I know this is a old question but here is another solution that works for me
SET #dtDate = "your date"
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,#dtDate)+1,0))
And if some one is looking for different examples here is a link http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
I hope this helps some one else.
stackoverflow Rocks!!!!
For SQL server 2012 or above use EOMONTH to get the last date of month
SQL query to display end date of current month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate) AS CurrentMonthED
SQL query to display end date of Next month
DECLARE #currentDate DATE = GETDATE()
SELECT EOMONTH (#currentDate, 1 ) AS NextMonthED
Based on the statements:
SELECT DATEADD(MONTH, 1, #x) -- Add a month to the supplied date #x
and
SELECT DATEADD(DAY, 0 - DAY(#x), #x) -- Get last day of month previous to the supplied date #x
how about adding a month to date #x and then retrieving the last day of the month previous to that (i.e. The last day of the month of the supplied date)
DECLARE #x DATE = '20-Feb-2012'
SELECT DAY(DATEADD(DAY, 0 - DAY(DATEADD(MONTH, 1, #x)), DATEADD(MONTH, 1, #x)))
Note: This was test using SQL Server 2008 R2
Just extend your formula out a little bit:
dateadd(day, -1,
dateadd(month, 1,
cast(month('5/15/2009') as varchar(2)) +
'/1/' +
cast(year('5/15/2009') as varchar(4)))
This works for me, using Microsoft SQL Server 2005:
DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,'2009-05-01')+1,0))
WinSQL to get last day of last month (i.e today is 2017-02-09, returns 2017-01-31:
Select dateadd(day,-day(today()),today())
Try to run the following query, it will give you everything you want :)
Declare #a date =dateadd(mm, Datediff(mm,0,getdate()),0)
Print('First day of Current Month:')
Print(#a)
Print('')
set #a = dateadd(mm, Datediff(mm,0,getdate())+1,-1)
Print('Last day of Current Month:')
Print(#a)
Print('')
Print('First day of Last Month:')
set #a = dateadd(mm, Datediff(mm,0,getdate())-1,0)
Print(#a)
Print('')
Print('Last day of Last Month:')
set #a = dateadd(mm, Datediff(mm,0,getdate()),-1)
Print(#a)
Print('')
Print('First day of Current Week:')
set #a = dateadd(ww, Datediff(ww,0,getdate()),0)
Print(#a)
Print('')
Print('Last day of Current Week:')
set #a = dateadd(ww, Datediff(ww,0,getdate())+1,-1)
Print(#a)
Print('')
Print('First day of Last Week:')
set #a = dateadd(ww, Datediff(ww,0,getdate())-1,0)
Print(#a)
Print('')
Print('Last day of Last Week:')
set #a = dateadd(ww, Datediff(ww,0,getdate()),-1)
Print(#a)
WinSQL: I wanted to return all records for last month:
where DATE01 between dateadd(month,-1,dateadd(day,1,dateadd(day,-day(today()),today()))) and dateadd(day,-day(today()),today())
This does the same thing:
where month(DATE01) = month(dateadd(month,-1,today())) and year(DATE01) = year(dateadd(month,-1,today()))
This query can also be used.
DECLARE #SelectedDate DATE = GETDATE()
SELECT DATEADD(DAY, - DAY(#SelectedDate), DATEADD(MONTH, 1 , #SelectedDate)) EndOfMonth
--## Useful Date Functions
SELECT
GETDATE() AS [DateTime],
CAST(GETDATE() AS DATE) AS [Date],
DAY(GETDATE()) AS [Day of Month],
FORMAT(GETDATE(),'MMMM') AS [Month Name],
FORMAT(GETDATE(),'MMM') AS [Month Short Name],
FORMAT(GETDATE(),'MM') AS [Month No],
YEAR(GETDATE()) AS [Year],
CAST(DATEADD(DD,-(DAY(GETDATE())-1),GETDATE()) AS DATE) AS [Month Start Date],
EOMONTH(GETDATE()) AS [Month End Date],
CAST(DATEADD(M,-1,DATEADD(MM, DATEDIFF(M,0,GETDATE()),0)) AS DATE) AS [Previous Month Start Date],
CAST(DATEADD(S,-1,DATEADD(MM, DATEDIFF(M,0,GETDATE()),0)) AS DATE) AS [Previous Month End Date],
CAST(DATEADD(M,+1,DATEADD(MM, DATEDIFF(M,0,GETDATE()),0)) AS DATE) AS [Next Month Start Date],
CAST(DATEADD(D,-1,DATEADD(MM, DATEDIFF(M,0,GETDATE())+2,0)) AS DATE) AS [Next Month End Date],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE()),0) AS DATE) AS [First Day of Current Week],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE())+1,-1) AS DATE) AS [Last Day of Current Week],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE())-1,0) AS DATE) AS [First Day of Last Week],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE()),-1) AS DATE) AS [Last Day of Last Week],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE())+1,0) AS DATE) AS [First Day of Next Week],
CAST(DATEADD(WW, DATEDIFF(WW,0,GETDATE())+2,-1) AS DATE) AS [Last Day of Next Week]
My 2 cents:
select DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(day,(0-(DATEPART(dd,'2008-02-12')-1)),'2008-02-12')))
Raj
using sql server 2005, this works for me:
select dateadd(dd,-1,dateadd(mm,datediff(mm,0,YOUR_DATE)+1,0))
Basically, you get the number of months from the beginning of (SQL Server) time for YOUR_DATE. Then add one to it to get the sequence number of the next month. Then you add this number of months to 0 to get a date that is the first day of the next month. From this you then subtract a day to get to the last day of YOUR_DATE.
Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the #dt value differs).
declare #dt datetime;
set #dt = '20140312'
SELECT DATEADD(month, DATEDIFF(month, '20011231', #dt), '20011231');
set #dt = '20140208'
SELECT DATEADD(month, DATEDIFF(month, '20011231', #dt), '20011231');
set #dt = '20140405'
SELECT DATEADD(month, DATEDIFF(month, '20011231', #dt), '20011231');
Using SQL Server, here is another way to find last day of month :
SELECT DATEADD(MONTH,1,GETDATE())- day(DATEADD(MONTH,1,GETDATE()))
I wrote following function, it works.
It returns datetime data type. Zero hour, minute, second, miliseconds.
CREATE Function [dbo].[fn_GetLastDate]
(
#date datetime
)
returns datetime
as
begin
declare #result datetime
select #result = CHOOSE(month(#date),
DATEADD(DAY, 31 -day(#date), #date),
IIF(YEAR(#date) % 4 = 0, DATEADD(DAY, 29 -day(#date), #date), DATEADD(DAY, 28 -day(#date), #date)),
DATEADD(DAY, 31 -day(#date), #date) ,
DATEADD(DAY, 30 -day(#date), #date),
DATEADD(DAY, 31 -day(#date), #date),
DATEADD(DAY, 30 -day(#date), #date),
DATEADD(DAY, 31 -day(#date), #date),
DATEADD(DAY, 31 -day(#date), #date),
DATEADD(DAY, 30 -day(#date), #date),
DATEADD(DAY, 31 -day(#date), #date),
DATEADD(DAY, 30 -day(#date), #date),
DATEADD(DAY, 31 -day(#date), #date))
return convert(date, #result)
end
It's very easy to use.
2 example:
select [dbo].[fn_GetLastDate]('2016-02-03 12:34:12')
select [dbo].[fn_GetLastDate](GETDATE())
Based on the most voted answer at below link I came up with the following solution:
declare #mydate date= '2020-11-09';
SELECT DATEADD(month, DATEDIFF(month, 0, #mydate)+1, -1) AS lastOfMonth
link: How can I select the first day of a month in SQL?
I couldn't find an answer that worked in regular SQL, so I brute forced an answer:
SELECT *
FROM orders o
WHERE (MONTH(o.OrderDate) IN ('01','03','05','07','08','10','12') AND DAY(o.OrderDate) = '31')
OR (MONTH(o.OrderDate) IN ('04','06','09','11') AND DAY(o.OrderDate) = '30')
OR (MONTH(o.OrderDate) IN ('02') AND DAY(o.OrderDate) = '28')
---Start/End of previous Month
Declare #StartDate datetime, #EndDate datetime
set #StartDate = DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0)
set #EndDate = EOMONTH (DATEADD(month, DATEDIFF(month, 0, GETDATE())-1,0))
SELECT #StartDate,#EndDate