query for first and last day of month - sql

If I have the name of the month, how can I have the first and last day of that month in SQL?
I have this query to returns the month names:
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SELECT #StartDate = '20110501'
,#EndDate = '20110801';
SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS MonthName
FROM master.dbo.spt_values x
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
Result:
Now, how can i get the first and last day of that months? changing the query.

If you want a more general and simple solution:
DECLARE #startdate AS DATETIME = GETDATE()
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, #startdate) , 0) as startMonth,
DATEADD(SECOND, -1, DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, #startdate) , 0) ) ) as endMonth
Gives the result:
startMonth endMonth
----------------------- -----------------------
2013-06-01 00:00:00.000 2013-06-30 23:59:59.000

Try this :-
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SELECT #StartDate = '20110501'
,#EndDate = '20110801';
SELECT DATENAME(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS MonthName,
CONVERT(VARCHAR(25),
DATEADD(dd,-(DAY(DATEADD(MONTH, x.number, #StartDate))-1),DATEADD(MONTH, x.number, #StartDate)),101) as FirstDay,
CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,DATEADD(MONTH, x.number, #StartDate)))),DATEADD(mm,1,DATEADD(MONTH, x.number, #StartDate))),101) as LastDay
FROM master..spt_values x
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
Result :-
MonthName FirstDay LastDay
May 05/01/2011 05/31/2011
June 06/01/2011 06/30/2011
July 07/01/2011 07/31/2011
August 08/01/2011 08/31/2011
Result obtained taking the help from this query

This code gives you the first date of Current Month:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
If you know the Month's number then:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + #MonthNumber, 0)
Same goes for Month's end date :
SELECT DATEADD(MILLISECOND, -1,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - ##MonthNumber+ 1, 0))

Related

Get Year of parameter dates

Is there a way for me to get the year of the months based on the parameter given?
DECLARE #StartDate DATETIME,
#EndDate DATETIME;
SELECT
#StartDate = '2016-02-01',
#EndDate = '2017-03-01';
SELECT
/*is there a way for me to get the year of months based on the parameter dates*/
/*DATEPART(YEAR, DATEADD(YEAR, x.number, #StartDate)) AS Year,*/
DATEPART(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS Month,
DATENAME(MONTH, DATEADD(MONTH, x.number, #StartDate)) AS MonthName
FROM
master.dbo.spt_values x
WHERE
x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
The result of my query....
What I want is that from february to december it'll have a year of 2016 and from january to march it'll have a 2017 year..... based on the parameter that I've given..
Thanks in advance.
Try this:
SELECT YEAR(y.dt) AS Year,
MONTH(y.dt) AS Month,
DATENAME(MONTH, y.dt) AS MonthName
FROM master.dbo.spt_values x
CROSS APPLY (SELECT DATEADD(MONTH, x.number, #StartDate)) AS y(dt)
WHERE x.type = 'P'
AND x.number <= DATEDIFF(MONTH, #StartDate, #EndDate)
Demo here

Accumulating data from previous year

I'm having trouble with finding a solution for below SQL-query. My first query should and does the trick of accumulating amount of last year's data.
CASE
WHEN rehuv.VER_DATUM >= dateadd(year, -1, dateadd(month, -datepart(month, #STARTDATE) + 1, #STARTDATE))
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_ACC
But when I try to accumulate data within a specific time interval (I want the same time interval as #startdate -> #enddate but one year backwards). Sql-query:
CASE
WHEN rehuv.VER_DATUM >= DATEADD(year, -1, #STARTDATE)
AND rehuv.VER_DATUM <= DATEADD(year, -1, #ENDDATE) THEN rehuv.BELOPP ELSE 0
END AS PREVIOUS_YEAR_MONTH
Thank you in advance!
Best regards,
Simon
If you want the monthly sum of last year, you can try this:
DECLARE #STARTDATE DATETIME;
DECLARE #ENDDATE DATETIME;
SET #STARTDATE='2015-1-1';
SET #ENDDATE='2015-5-1';
DECLARE #LAST_YEAR DATE;
SET #LAST_YEAR = DATEADD(YEAR, -1, DATEADD(DAY,
DATEPART(DAYOFYEAR, GETDATE())*-1+1, CONVERT(DATE, GETDATE())));
SELECT DATEADD(MONTH, DATEPART(MONTH, VER_DATUM), #LAST_YEAR) MONTH, SUM(CASE
WHEN REHUV.VER_DATUM >= DATEADD(YEAR, -1, #STARTDATE)
AND REHUV.VER_DATUM <= DATEADD(YEAR, -1, #ENDDATE)
THEN REHUV.BELOPP ELSE 0
END ) AS PREVIOUS_YEAR_MONTH
FROM REHUV
GROUP BY DATEPART(MONTH, VER_DATUM)

SQL Last Three Months

I have wrote SQL to select user data for last three months, but I think at the moment it updates daily.
I want to change it so that as it is now October it will not count Octobers data but instead July's to September data and change to August to October when we move in to November
This is the SQL I got at the moment:
declare #Today datetime
declare #Category varchar(40)
set #Today = dbo.udf_DateOnly(GETDATE())
set #Category = 'Doctors active last three months updated'
declare #last3monthsnew datetime
set #last3monthsnew=dateadd(m,-3,dbo.udf_DateOnly(GETDATE()))
delete from LiveStatus_tbl where Category = #Category
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
WHERE LastLoggedIn >= #last3monthsnew
How would I edit this to do that?
WHERE LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
The above statement will return any results in July till before the start of current month.
Referencing this answer to get the first day of the month:
How can I select the first day of a month in SQL?
You can detect the month limitations like so:
select DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0) AS StartOfMonth
select DATEADD(month, DATEDIFF(month, 0, getdate()), 0) AS EndMonth
Then you can add that into variables or directly into your WHERE clause:
declare #StartDate datetime
declare #EndDate datetime
set #StartDate = DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
set #EndDate = DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= #StartDate AND LastLoggedIn < #EndDate
Or:
select #Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
and LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
How about using BETWEEN ?
WHERE LastLoggedIn
BETWEEN
DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)

SQL - Get data based on months form a dateTime column

With SQL Server, I have a column with a launch date (dateTime). I want to report on everything that is being launched between all of last month (from viewing date) thru all of this month and next month.
So basically a full 3 month period.
What is the best way to write that?
Are you looking for something like this?
DECLARE
#StartDate DATETIME,
#EndDate DATETIME
SELECT
#StartDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0),
#EndDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0)
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0), -- beginning of this month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0), -- beginning of last month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0) -- beginning of next month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0) -- beginning of two months from now
SELECT
*
FROM
[Table]
WHERE
[LaunchDate] >= #StartDate
AND [LaunchDate] < #EndDate
This will give you all the results starting from the beginning of the previous month and before the beginning of two months from now (a full 3 month range)
Maybe something like SELECT /*what_you_want*/ from launches WHERE lauchDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101') AND DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 2, '19000101')
SELECT Foo
FROM Bar
WHERE LaunchDate >= DATEADD(mm, -1, GETDATE())
AND LaunchDate <= DATEADD(mm, 1, GETDATE())

How to get the last month data and month to date data

Need help in writing the query to get the last month data as well as month to date data.
If today's date is Mar 23 2011, I need to retrieve the data from last month and the data till todays date(means Mar 23 2011).
If date is Apr 3 2011, data should consists of March month data and the data till Apr 3rd 2011.
Thanks,
Shahsra
Today including time info : getdate()
Today without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 0)
Tomorrow without time info : DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Beginning of current month : DATEADD(month, datediff(month, 0, getdate()), 0)
Beginning of last month : DATEADD(month, datediff(month, 0, getdate())-1, 0)
so most likely
WHERE dateColumn >= DATEADD(month, datediff(month, 0, getdate())-1, 0)
AND dateColumn < DATEADD(DAY, DATEDIFF(day, 0, getdate()), 1)
Step back one month, subtract the number of days to the current date, and add one day.
WHERE
DateField <= GetDate() AND
DateField >= DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)
To remove the time quickly, you can use this
Cast( Floor( Cast( GETDATE() AS FLOAT ) ) AS DATETIME )
So the second part would be (without time)
DateField >= Cast( Floor( Cast( (DateAdd(
mm,
-1,
DateAdd(dd, -1*DatePart(dd, GetDate())+1, GetDate())
)) AS FLOAT ) ) AS DATETIME )
Select Column1, Column2 From Table1
Where DateColumn <= GetDate() AND
DateColumn >= DATEADD(dd, - (DAY(DATEADD(mm, 1, GetDate())) - 1), DATEADD(mm, - 1, GetDate()))
Edit: +1 to Russel Steen. I was posting mine before I knew he had posted.
Very helpful page
declare #d datetime = '2011-04-03';
declare #startDate datetime;
select #startDate =
CAST('01 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,#d),113),8) AS datetime);
select #startDate;