how to get automatically previous month date range in SQL? - sql

I have 2012 SQL Server stored procedure ran automatically every fifth of the month but the problem I have is supplying previous month date range e.g. I need to have clause like ...where datein between '2014-02-01' and '2014-02-28' and next month it would change it to ...where datein between '2014-03-01' and '2014-02-31' and so on.
thanks

This should work
SELECT DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) AS StartDate, EOMONTH(GETDATE(),-1) AS EndDate
To be more specific in your WHERE clause
WHERE #datein BETWEEN DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) AND EOMONTH(GETDATE(),-1)

You can use getdate() and some date arithmetic. Here is a relatively easy way:
where datein >= cast(dateadd(month, -1, getdate() - day(getdate()) + 1) as date) and
datein < cast(getdate() - day(getdate()) + 1)
The key idea here is to subtract the day of the month and add 1 to get the first day of the current month.

It is bad practice to use getdate(), instead across all application use getutcdate()
WHERE #datein BETWEEN DATEADD(DAY,1,EOMONTH(GETUTCDATE(),-2)) AND EOMONTH(GETUTCDATE(),-1)

Here is a way to do this so your dates will be greater than the beginning of this month and less than the beginning of next month.
datein >= dateadd(month, datediff(month, 0, getdate()), 0) --BeginningOfThisMonth
and datein < dateadd(month, datediff(month, 0, getdate()) + 1, 0) --BeginningOfNextMonth

This worked for my current version of mysql:
SELECT DATE_ADD(LAST_DAY(DATE_SUB(current_date, INTERVAL 2 MONTH)), INTERVAL 1 DAY) AS StartDate,
LAST_DAY(DATE_SUB(current_date, INTERVAL 1 MONTH)) AS EndDate;

might try this for Feb as original only went to 27th of Feb
BETWEEN DATEADD(DAY,1,EOMONTH(GETDATE(),-2)) AND DATEADD(DAY,1,EOMONTH(GETDATE(),-1))

Please try
DECLARE #date date=GETDATE()
SELECT DATEADD(DAY,1,EOMONTH(#date,-2)) AS StartDate, EOMONTH(#date,-1) AS EndDate

Related

date format : get the last and the first day in the month-sql-DB2

how i can write the following date with date function.. IN DB2
L2.FOM >= '2015-08-01' // the first day of the current Month
L2.TOM <= '2015-08-31' // the last day of the current Month
i tried this but it doesnot work
L2.FOM=DATEADD(month,DATEDIFF(month,0,CURRENT DATE), 0) //for the first day of the month
last date
DECLARE #date DATETIME = '12/1/2011';
SELECT EOMONTH ( #date ) AS Result;
GO
first date - is known to start from 1.
but here it is for name sake.
SELECT DATEADD(month, DATEDIFF(month, 0, #date), 0) AS StartOfMonth
Your code looks like SQL Server.
In that database, I would suggest using eomonth():
select eomonth(getdate()) as last_date_of_month,
dateadd(day, 1, eomonth(getdate(), -1)) as first_date_of_month
For the first date of the month, I also often use:
datefromparts(year(getdate()), month(getdate()), 1)

How to get data for the last week data?

I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?
SET DATEFIRST 1
select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE< dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
Thanks.
select * from table_abc WHERE
CAST(CONTRACT_UPDATE_DATE as date) between
CAST(DATEADD(dd, -7, GETDATE()) as date) and
CAST(GETDATE() AS DATE)
use dateadd to get 1 week before current date.
You can remove the cast as date if you need to validate by timestamp also.
You can try this,
SELECT Created_Date
FROM sample1
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
I suggest this solution:
select * from DB where Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))<=7 and Datediff(day, CONVERT(DATE, Sysdatetime()),
CONVERT(DATE, CONTRACT_UPDATE_DATE))>0
You could try to achieve this by using the calender week.
Try the following:
-- Get last calendar week in format JJJJWW
DECLARE #jjjjkw varchar(6)
SELECT #jjjjkw =
CONVERT(varchar, DATEPART(YYYY,GETDATE()-7)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))) = 1 THEN '0'
+ CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,GETDATE()-7)) END
-- Compare with the calendar week of your data-set
SELECT DISTINCT [...]
WHERE
CONVERT(varchar, DATEPART(YYYY,CONTRACT_UPDATE_DATE)) +
CASE WHEN LEN(CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))) = 1
THEN '0' + CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE))
ELSE CONVERT(varchar,DATEPART(ISO_WEEK,CONTRACT_UPDATE_DATE)) END = #jjjjkw
Maybe not the most elegant way but it should work.

Getdate() functionality returns partial day in select query

I have a query -
SELECT * FROM TABLE WHERE Date >= DATEADD (day, -7, -getdate()) AND Date <= getdate();
This would return all records for each day except day 7. If I ran this query on a Sunday at 17:00 it would only produce results going back to Monday 17:00. How could I include results from Monday 08:00.
Try it like this:
SELECT *
FROM SomeWhere
WHERE [Date] > DATEADD(HOUR,8,DATEADD(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))) --7 days back, 8 o'clock
AND [Date] <= GETDATE(); --now
That's because you are comparing date+time, not only date.
If you want to include all days, you can trunc the time-portion from getdate(): you can accomplish that with a conversion to date:
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -convert(date, getdate())
AND Date <= convert(date, getdate());
If you want to start from 8 in the morning, the best is to add again 8 hours to getdate.
declare #t datetime = dateadd(HH, 8, convert(datetime, convert(date, getdate())))
SELECT * FROM TABLE
WHERE Date >= DATEADD (day, -7, -#t) AND Date <= #t;
NOTE: with the conversion convert(date, getdate()) you get a datatype date and you cannot add hours directly to it; you must re-convert it to datetime.
Sounds like you want to remove the time. Correct? If so then do the following.
SELECT * FROM TABLE WHERE Date >= (DATEADD (day, -7, -getdate()) AND Date DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0))

How to run a query for "Today's" date from 12:00am to 11:59PM

I have a simple query that pulls a payout report for our day. I'd like to automate this to send every night, however I want the report to run for That day 12:00AM - 11:59 PM daily... I will be sending the reports at 9:00 PM, so I suppose it will only need to get until 9:00 PM if that's easier.
Here is my query:
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated BETWEEN #startdate AND #enddate)
Don't use BETWEEN, use >= the start date and < a day past the end date:
WHERE (dtCreated >= #startdate AND dtCreated < DATEADD(day, 1, #enddate))
The reason is that BETWEEN will find up until 12:00am of the end date, but not past then.
UPDATED
For todays date, you can do this:
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, dtCreated)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
This will check that it has a dtCreated equal to some point today.
UPDATED
As #ScottChapman has pointed out, you can do the same thing without the conversion gymnastics by casting to the DATE type directly. This type is only available in MSSQL 2008 and later, however.
SET #StartDate = CAST(GETDATE() AS date)
SET #EndDate = DATEADD(MINUTE, -1, DATEADD(DAY, 1, #StartDate))
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated BETWEEN #startdate AND #enddate)
Some of these answers are close, but exclude times in the final minute of the day, like 11:59:30 PM. This query will include all of today:
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE (dtCreated >= CAST(GETDATE() as date) AND dtCreated < DATEADD(day, 1, CAST(GETDATE() as date)))
Note that this won't work in SQL Server 2005 or below, as the date type was added in SQL Server 2008.
As you're using SQL/Server 2008 you can remove any time element from a DATETIME column by converting it to DATE and select on that, E.g.
SELECT COUNT(*) AS Number, SUM(dblPayoutAmt) AS Amount
FROM Payouts
WHERE CONVERT(DATE,dtCreated) = CONVERT(DATE,GETDATE())
Very much more elegant
[EDIT]
Oh, I've just read Scott Chapman's answer, it's better because if dtCreated is indexed then the query will be more efficient.
Preceding answers also include data < 12.00 am
SELECT
COUNT(*) AS Number
, SUM(dblPayoutAmt) AS Amount
FROM
Payouts
WHERE
dtCreated >= dateadd( hour, 12, cast( cast( getdate() as date ) as datetime ))
and dtCreated < dateadd( second, -1, dateadd(day, datediff(day, -1, getdate()), 0))
set them both to SIMPLE date example: BETWEEN '2012-12-19' AND '2012-12-20' with no timestamp on them, then select the between.
In this example if you set the date for end to '2012-12-20 23:59:59.999' and then do a SELECT #enddate it returns '2012-12-21 00:00:00.000'
OR to use a function type syntax:
declare #mystart as datetime
declare #myend as datetime
set #mystart = dateadd(day,datediff(day,0,CURRENT_TIMESTAMP),0)
set #myend = dateadd(day,datediff(day,0,CURRENT_TIMESTAMP),1)
select #mystart, #myend
the #mystart here is set to ONLY the date part (time is 00:00:00.000) and the end is sent to that plus one day, so the BETWEEN syntax works.

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