Select records from start of month to current date - sql-server-2005

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

Related

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.

how to get automatically previous month date range in 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

How to grab data from the last 13 months?

So I have this code, this is for grabbing data for the last 11 month of sale including the current month, make it a whole year. What do I have to do to change it to grabbing data for the last 12 months plus current month? I know I have to change something on the right(select period)... but not sure
In this one, the left function shows how to get the current year (2014 ) minus 1 to give 2013.. but I don't understand the right function, what does 2 mean?
Thanks
period <= (
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))) and period >= (
convert(varchar, left((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),4)-1)+'-'+
convert(varchar, right((
SELECT Period
FROM dbo.FiscalDates
WHERE (Date = CONVERT(varchar(10), GETDATE(), 102))),2)))
group by prodnum, period, WhseNum
Whoah buddy I think you may be overcomplicating things here. If you want to get data for the past X number of months then just use DATEADD it's a very useful function.
All you need to do then is
select
YourColumns
FROM YourTable
WHERE YourDate >= DATEADD(MONTH, -13, CAST(GETDATE() AS DATE))
and bam there you go.
DECLARE
#FormYear AS INT,
#FormMonth AS INT,
#ToYear AS INT,
#ToMonth AS INT,
#FromDate AS DATE,
#ToDate AS DATE
SET #FormYear=YEAR(DATEADD(DAY, -365, GETDATE()))
SET #FormMonth=MONTH(DATEADD(DAY, -365, GETDATE()))
SET #ToYear=YEAR(GETDATE())
SET #ToMonth=MONTH(GETDATE())
SET #FromDate= CAST(CAST(#FormMonth AS VARCHAR) +'-'+'01'+ '-' +CAST(#FormYear AS VARCHAR) AS DATE)
SET #ToDate= CAST(CAST(#ToMonth AS VARCHAR) +'-' + '01'+'-' + CAST(#ToYear AS VARCHAR) AS DATE)
After that, just select-
YourDateField Between #FormDate AND #ToDate

first day of the same month

I have a date parameter (#rptMonth) that is selected by the user from a datepicker calendar. The date must be the first day of the month. No matter what the user selects I'd like to turn that into mm/01/yyyy. For example- I need the first day of the month. So if the user selects 06/22/2010, I need to turn that into 06/01/2010. So in my query it would be something like WHERE YEAR_MONTH = DATEADD("m",datediff("m","1900-01-01",#RptMonth),"1900-01-01"),"mm/dd/yyyy" but when I try this I get incorrect syntax near ','. Don't know if this will even work.
Update:
select dateadd(month, datediff(month, 0, getdate()), 0)
Older:
Try this:
declare #arbitraryDate datetime;
set #arbitraryDate = getdate();
set #arbitraryDate = dateadd(dd, datediff(dd, 0, #arbitraryDate), 0) --strip time
select dateadd(dd, -day(#arbitraryDate)+1,#arbitraryDate) --strip days
Or this:
select cast(convert(varchar(6), getdate(), 112) + '01' as datetime)
This should work too:
SELECT CAST(CAST(YEAR(#pInputDate) AS VARCHAR(4)) +
CAST(MONTH(#pInputDate) AS VARCHAR(2)) + '01' AS DATETIME)

Get the records of last month in SQL server

I want to get the records of last month based on my db table [member] field "date_created".
What's the sql to do this?
For clarification,
last month - 1/8/2009 to 31/8/2009
If today is 3/1/2010, I'll need to get the records of 1/12/2009 to 31/12/2009.
All the existing (working) answers have one of two problems:
They will ignore indices on the column being searched
The will (potentially) select data that is not intended, silently corrupting your results.
1. Ignored Indices:
For the most part, when a column being searched has a function called on it (including implicitly, like for CAST), the optimizer must ignore indices on the column and search through every record. Here's a quick example:
We're dealing with timestamps, and most RDBMSs tend to store this information as an increasing value of some sort, usually a long or BIGINTEGER count of milli-/nanoseconds. The current time thus looks/is stored like this:
1402401635000000 -- 2014-06-10 12:00:35.000000 GMT
You don't see the 'Year' value ('2014') in there, do you? In fact, there's a fair bit of complicated math to translate back and forth. So if you call any of the extraction/date part functions on the searched column, the server has to perform all that math just to figure out if you can include it in the results. On small tables this isn't an issue, but as the percentage of rows selected decreases this becomes a larger and larger drain. Then in this case, you're doing it a second time for asking about MONTH... well, you get the picture.
2. Unintended data:
Depending on the particular version of SQL Server, and column datatypes, using BETWEEN (or similar inclusive upper-bound ranges: <=) can result in the wrong data being selected. Essentially, you potentially end up including data from midnight of the "next" day, or excluding some portion of the "current" day's records.
What you should be doing:
So we need a way that's safe for our data, and will use indices (if viable). The correct way is then of the form:
WHERE date_created >= #startOfPreviousMonth AND date_created < #startOfCurrentMonth
Given that there's only one month, #startOfPreviousMonth can be easily substituted for/derived by:
DATEADD(month, -1, #startOfCurrentMonth)
If you need to derive the start-of-current-month in the server, you can do it via the following:
DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
A quick word of explanation here. The initial DATEDIFF(...) will get the difference between the start of the current era (0001-01-01 - AD, CE, whatever), essentially returning a large integer. This is the count of months to the start of the current month. We then add this number to the start of the era, which is at the start of the given month.
So your full script could/should look similar to the following:
DECLARE #startOfCurrentMonth DATETIME
SET #startOfCurrentMonth = DATEADD(month, DATEDIFF(month, 0, CURRENT_TIMESTAMP), 0)
SELECT *
FROM Member
WHERE date_created >= DATEADD(month, -1, #startOfCurrentMonth)
AND date_created < #startOfCurrentMonth
All date operations are thus only performed once, on one value; the optimizer is free to use indices, and no incorrect data will be included.
SELECT *
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, date_created) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
You need to check the month and year.
Add the options which have been provided so far won't use your indexes at all.
Something like this will do the trick, and make use of an index on the table (if one exists).
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = dateadd(mm, -1, getdate())
SET #StartDate = dateadd(dd, datepart(dd, getdate())*-1, #StartDate)
SET #EndDate = dateadd(mm, 1, #StartDate)
SELECT *
FROM Member
WHERE date_created BETWEEN #StartDate AND #EndDate
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm, DATEDIFF(mm,0,getdate())-1, 0)
SET #EndDate = DATEADD(mm, 1, #StartDate)
SELECT *
FROM Member
WHERE date_created BETWEEN #StartDate AND #EndDate
An upgrade to mrdenny's solution, this way you get exactly last month from YYYY-MM-01
Last month consider as till last day of the month.
31/01/2016 here last day of the month would be 31 Jan. which is not similar to last 30 days.
SELECT CONVERT(DATE, DATEADD(DAY,-DAY(GETDATE()),GETDATE()))
One way to do it is using the DATEPART function:
select field1, field2, fieldN from TABLE where DATEPART(month, date_created) = 4
and DATEPART(year, date_created) = 2009
will return all dates in april. For last month (ie, previous to current month) you can use GETDATE and DATEADD as well:
select field1, field2, fieldN from TABLE where DATEPART(month, date_created)
= (DATEPART(month, GETDATE()) - 1) and
DATEPART(year, date_created) = DATEPART(year, DATEADD(m, -1, GETDATE()))
declare #PrevMonth as nvarchar(256)
SELECT #PrevMonth = DateName( month,DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)) +
'-' + substring(DateName( Year, getDate() ) ,3,4)
SQL query to get record of the present month only
SELECT * FROM CUSTOMER
WHERE MONTH(DATE) = MONTH(CURRENT_TIMESTAMP) AND YEAR(DATE) = YEAR(CURRENT_TIMESTAMP);
SELECT * FROM Member WHERE month(date_created) = month(NOW() - INTERVAL 1 MONTH);
select * from [member] where DatePart("m", date_created) = DatePart("m", DateAdd("m", -1, getdate())) AND DatePart("yyyy", date_created) = DatePart("yyyy", DateAdd("m", -1, getdate()))
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm, DATEDIFF(mm, 0, getdate()) - 1, 0)
SET #EndDate = dateadd(dd, -1, DATEADD(mm, 1, #StartDate))
SELECT * FROM Member WHERE date_created BETWEEN #StartDate AND #EndDate
and another upgrade to mrdenny's solution.
It gives the exact last day of the previous month as well.
WHERE
date_created >= DATEADD(MONTH, DATEDIFF(MONTH, 31, CURRENT_TIMESTAMP), 0)
AND date_created < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
I'm from Oracle env and I would do it like this in Oracle:
select * from table
where trunc(somedatefield, 'MONTH') =
trunc(sysdate -INTERVAL '0-1' YEAR TO MONTH, 'MONTH')
Idea: I'm running a scheduled report of previous month (from day 1 to the last day of the month, not windowed). This could be index unfriendly, but Oracle has fast date handling anyways.
Is there a similar simple and short way in MS SQL? The answer comparing year and month separately seems silly to Oracle folks.
You can get the last month records with this query
SELECT * FROM dbo.member d
WHERE CONVERT(DATE, date_created,101)>=CONVERT(DATE,DATEADD(m, datediff(m, 0, current_timestamp)-1, 0))
and CONVERT(DATE, date_created,101) < CONVERT(DATE, DATEADD(m, datediff(m, 0, current_timestamp)-1, 0),101)
I don't think the accepted solution is very index friendly
I use the following lines instead
select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date <= dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));
Or simply (this is the best).
select * from dbtable where the_date >= convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120) and the_date < SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
Some help
-- Get the first of last month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
-- Get the first of current month
SELECT convert(varchar(10),DATEADD(m, -1, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120);
--Get the last of last month except the last 3milli seconds. (3miliseconds being used as SQL express otherwise round it up to the full second (SERIUSLY MS)
SELECT dateadd(ms, -3, convert(varchar(10),DATEADD(m, 0, dateadd(d, - datepart(dd, GETDATE())+1, GETDATE())),120));
Here is what I did so I could put it in a view:
ALTER view [dbo].[MyView] as
with justdate as (
select getdate() as rightnow
)
, inputs as (
select dateadd(day, 1, EOMONTH(jd.rightnow, -2)) as FirstOfLastMonth
,dateadd(day, 1, EOMONTH(jd.rightnow, -1)) as FirstOfThisMonth
from justdate jd
)
SELECT TOP 10000
[SomeColumn]
,[CreatedTime]
from inputs i
join [dbo].[SomeTable]
on createdtime >= i.FirstOfLastMonth
and createdtime < i.FirstOfThisMonth
order by createdtime
;
Note that I intentionally ran getdate() once.
In Sql server for last one month:
select * from tablename
where order_date > DateAdd(WEEK, -1, GETDATE()+1) and order_date<=GETDATE()
DECLARE #curDate INT = datepart( Month,GETDATE())
IF (#curDate = 1)
BEGIN
select * from Featured_Deal
where datepart( Month,Created_Date)=12 AND datepart(Year,Created_Date) = (datepart(Year,GETDATE())-1)
END
ELSE
BEGIN
select * from Featured_Deal
where datepart( Month,Created_Date)=(datepart( Month,GETDATE())-1) AND datepart(Year,Created_Date) = datepart(Year,GETDATE())
END
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = dateadd(mm, -1, getdate())
SET #StartDate = dateadd(dd, datepart(dd, getdate())*-1, #StartDate)
SET #EndDate = dateadd(mm, 1, #StartDate)
set #StartDate = DATEADD(dd, 1 , #StartDate)
The way I fixed similar issue was by adding Month to my SELECT portion
Month DATEADD(day,Created_Date,'1971/12/31') As Month
and than I added WHERE statement
Month DATEADD(day,Created_Date,'1971/12/31') = month(getdate())-1
If you are looking for last month so try this,
SELECT
FROM #emp
WHERE DATEDIFF(MONTH,CREATEDDATE,GETDATE()) = 1
If you are looking for last month so try this,
SELECT
FROM #emp
WHERE DATEDIFF(day,CREATEDDATE,GETDATE()) between 1 and 30
A simple query which works for me is:
select * from table where DATEADD(month, 1,DATEFIELD) >= getdate()
If you are looking for previous month data:
date(date_created)>=date_sub(date_format(curdate(),"%Y-%m-01"),interval 1 month) and
date(date_created)<=date_sub(date_format(curdate(),'%Y-%m-01'),interval 1 day)
This will also work when the year changes. It will also work on MySQL.