SQL query to find last day of current month? - sql

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
Hi everyone I have a query to find the last day of current month, which is surely working well, but I am unable to understand it, because I have other similar requirements and have to change it accordingly.
Can somebody explain it to me..
Thanks in advance

Get the DateTime of Now
GETDATE() -- 2011-09-15 13:45:00.923
Calculate the difference in month's from '1900-01-01'
DATEDIFF(m, 0, GETDATE()) -- 1340
Add the difference to '1900-01-01' plus one extra month
DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0) -- 2011-10-01 00:00:00.000
Remove one second
DATEADD(s, -1, DATEADD(m, DATEDIFF(m, 0, GETDATE())+1, 0)) -- 2011-09-30 23:59:59.000

This will give you the last day of current month but ignores time
select EOMONTH(GETDATE())
From Microsoft tech net

CREATE FUNCTION EOMONTH
(
#date datetime,
#months int
)
RETURNS datetime
AS
BEGIN
declare #eom datetime
declare #d datetime
set #d = dateadd(MONTH, #months, #date)
select #eom = dateadd(SECOND,-1,DATEADD(MONTH,datediff(MONTH,0,#d)+1,0))
RETURN #eom
END
GO

SELECT DATEPART (DD,EOMONTH(GETDATE())) AS 'the last day of the Current month'
Here DATEPART function is used to print the integer part of day.. if the the name of day is asked then we have to use DATENAME() function.
In query, last day means end of the month so we used EOMONTH() function.
GETDATE() is to represent current month.

Related

How to filter my results so it shows the last four months of data - sql

I'm trying to create a stored procedure that gets the last 4 months worth of results from the below query but I'm unsure how to do this.
This is what I have done so far:
Declare #Number varchar(30) = '12'
Select
month = month(EndDate),
YEAR = YEAR(EndDate),
SUM(DownloadUnits) as downloads,
SUM(UploadUnits) as uploads,
number
from testTable
where number=#Number
GROUP BY MONTH(EndDate), Year(Enddate),number
How can I filter it out so that when I pass month parameter (I haven't created it yet) it filters out the results so it only shows the last four months? (I have hard coded the number parameter for testing)
The last N months from now meet the condition
where EndDate >= dateadd(month, -#DEDUCT_MONTHS, cast(getdate() as DATE))
Removing the cast will enforce the current time as a constraint as opposed to midnight N months ago.
If you need to get whole months then you will need to get the first of the month 4 months ago.
You can get the first of the current month using:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
Adapting this slightly will give you the first of the month 4 months ago:
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 4, '19000101');
Then you can just apply this filter to your query:
WHERE EndDate >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 4, '19000101')
Or if you need to pass the number of months a parameter (it should be an INT not a varchar by the way):
WHERE EndDate >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - #Number, '19000101')
If you pass a date parameter, just replace GETDATE() with your parameter name.
DECLARE #StartDate date
SET #StartDate=Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, getdate())), 0)
--first day of the month, (current month-6 month)
The script above will return with the first day of the month - 6 month ago .
This solution is from stackoverflow somewhere, unfortunately I dont seem to find the original post.. :(
To understand how it works try to reverse-engineer as per follows:
DECLARE #StartDate1 date
SET #StartDate1= DATEADD(m, -6, getdate())
PRINT #Startdate1
DECLARE #StartDate2 int
SET #StartDate2= Datediff(Month, 0, DATEADD(m, -6, getdate()))
PRINT #Startdate2
DECLARE #StartDate3 date
SET #StartDate3=Dateadd(Month, 1369, 0)
PRINT #Startdate3

SQL Server: explanation needed to understand combination of DATEADD and DATEDIFF

I am pretty new to SQL and use the following lines within a Select in order to get the first and last Monday of October (#selYear defines the year).
Can someone here tell me how to adjust this so that it returns the second, third and fourth Monday of October + provide me an explanation so that I can modify this further for other dates ?
Do I just have to change the last 0 in the first formula to 7, 14 or 21 in order to add the additional weeks ?
And if instead of Monday I want Friday or Thursday would I then just replace the 6 by 4 or 3 ?
--1st Monday in October
DATEADD(d, DATEDIFF(d, 0, DATEADD(m, 10-1, DATEADD(yy, DATEDIFF(yy, 0, #selYear), 6)))/7*7, 0),
--last Monday in October
DATEADD(d, DATEDIFF(d, 0, DATEADD(m, 10, DATEADD(yy, DATEDIFF(yy, 0, #selYear), 6)))/7*7, -7),
Edit: #selYear in my case is defined as #selYear nvarchar(4) and the table column I am inserting this into is formatted as datetime - maybe this is wrong as the result should always be a valid date ?
Many thanks in advance, Mike.
declare #date as date = '20141001' -- this is for october 2014
declare #n as int = 0
while (#n<7)
begin
if ((select DATENAME(dw,#date)) = 'Monday') -- write which day you want as pivot
break
else
begin
set #n = #n+1
set #date = DATEADD(D,1,#date)
end
end
select #date first
, DATEADD(D,7,#date) second
, DATEADD(D,14,#date) third
, DATEADD(D,21,#date) fourth

Specific day of current month and year

I have problem with return of specific day of current month and year. I need for example 15th day. Until now I used in FB/IB existing function:
IB_EncodeDate(EXTRACT(YEAR FROM Current_Date),EXTRACT(Month FROM Current_Date),15)
Does it exist a simply way to convert this for MSSQL database?
edit. I need output in OLE format (41,348 by example) to compare date with another date. I compare date from database with 15th day of current month.
For the 15th day of current month:
SELECT DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0));
To get the silly OLE representation based on this "magic" date, 1899-12-30:
SELECT DATEDIFF(DAY, -2, DATEADD(DAY, 14,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)));
Answer (on March 11th, when I updated this answer for the changed requirement):
-----
41348
So, you have a date, and want to return the 15th day of the same month?. Well, assuming SQL Server 2008, you could do this:
SELECT CONVERT(DATE,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
For Previous versions of SQL Server:
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(6),GETDATE(),112)+'15',112)
This seems like a quick answer.
declare #OLEDate int
declare #currentDate as datetime
set #currentDate = DATEADD(DAY, 14, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
set #OLEDate = convert(float, #currentdate)
-- PRINT #OLEDate
based on Aaron Bertrand's answer and your need for the integer conversion
To get 10th day of current day
declare #cur_month int,#cur_yr int,#tenth_dt date
set #cur_month=month(getdate())
set #cur_yr=YEAR(getdate())
set #tenth_dt=convert(date,'10/'+convert(varchar(5),#cur_month)+'/'+convert(varchar(5),#cur_yr),103)
select #tenth_dt
Not sure if you after Day or Date. This gives both dayOfWeek and specificDate for any culture
declare #myDay int = 15
select convert(date,myday) specificDate, datename(dw,myday) dayOfWeek
from (
select convert(varchar(6),getdate(),112) + convert(varchar, #myDay) myday
) x
Fiddle Demo Here
| SPECIFICDATE | DAYOFWEEK |
----------------------------
| 2013-02-15 | Friday |
Current_Date in SQL Server would be getdate().
To get the 15th day in OLE Automation format, try:
select datediff(day, '18991230', dateadd(day, -day(getdate()) + 15, getdate()))
A bit more straightforward approach:
CAST(FORMAT(GETDATE(), 'yyyy-MM-15') AS DateTime)

Select records from start of month to current date

I'm trying to select records that were added to the database between the start of the current month and the current day - I more or less know how to get records from the current day, and within a specific time period - but how do I get it so it starts from the beginning of the current calendar month?
DECLARE #sm DATETIME;
SET #sm = DATEADD(DAY, 1-DAY(GETDATE()), DATEDIFF(DAY, 0, GETDATE()));
SELECT columns
FROM dbo.foo
WHERE datetime_column >= #sm;
WHERE YEAR([Date])=YEAR(GETDATE())
AND MONTH([Date])=MONTH(GETDATE())
AND DAY([Date])<=DAY(GETDATE())
select *
from YourTable
where DateCol >= dateadd(month, datediff(month, 0, getdate()), 0)
Basically what you're doing here is Getting the Month, appending '/01' and then appending the year. Casting it as a string to handle the appending, then casting it as a DateTime.
So it's a little bit more involved than doing any sort of date math, but it's readable I think.
DECLARE #firstOfMonth DATETIME
SET #firstOfMonth = CAST(CAST(DATEPART(mm, GetDate()) as varchar) + '/01/' + cast(DATEPART(yyyy, Getdate()) as varchar) as datetime)
WHERE DateToCheck BETWEEN #firstOfMonth and GetDate()
WHERE DateToCheck > LAST_DAY(CURDATE()-INTERVAL 1 MONTH))
http://www.sqlfiddle.com/#!2/3d673/2/0

last day of month question

I have the following query which is giving the last day of month by passing month name and year but dont know how to get first day in the similar fashion.
declare #month int, #year int
select #month=1,#year=2011
select Convert(varchar(20),dateadd(year,#year-1900,dateadd(month,#month,0)-1), 105)
I don't have experience with SQL Server, but based on your code, I would guess the answer would be something like:
declare #month int, #year int
select #month=1,#year=2011
select Convert(varchar(20),dateadd(year,#year-1900,dateadd(month,#month-1,0)), 105)
Keeping it in the datetime domain, find 1st day of following month and then subtract one day
SELECT
dateadd(day, -1, dateadd(year, #year-1900, dateadd(month, #month, 0)))
Almost anything with CAST or varchar is non-deterministic and isn't language/#DATEFORMAT safe