T-SQL: How to get all records prior to the first day of the current month? - sql

Using SQL Server: I am trying to find all records prior to the first day of the current month and set this as a parameter in an SSRS report (so I can't use a static value).
So, I need all records prior to the first day of the each current month going forward in column CREATEDDATETIME ('yyyy-mm-dd').
I have seen a lot of threads on how to find records for a specific month and various other searches but none specifically related to the above. Interested to see if the EOMONTH function will be of use here.
Thanks for the help and advice.

Here is an expression to use EOMONTH() function with optional parameter -1.
Explanations:
DateAdd: add 1 day to expression
getdate is current date
EOMONTH is end day of a given month; however, if you put an optional integer -1, this would mean last month
Thus: first day of current month is add one day to end of day last month
SELECT DATEADD(DAY,1,EOMONTH(getdate(),-1));
Result: 2018-04-01
SO in your query:
select *
from table
where CREATEDDATETIME < DATEADD(DAY,1,EOMONTH(getdate(),-1));

I would use datefromparts():
select t.*
from t
where CREATEDDATETIME < datefromparts(year(getdate()), month(getdate()), 1);

There's already two other answers that work, but for completeness here is a third common technique:
SELECT *
FROM [table]
WHERE CREATEDDATETIME < dateadd(month, datediff(month,0, current_timestamp), 0)
You might also get answers suggesting you build the date using strings. Don't do that. It's both the least efficient and most error prone option you could use.

all three answers are great, how ever you may find that it will select all the data prior to the 1st day of the current month until the 1st Createdate. This could cause the report to take forever to run, Maybe building in a limitation to the code I would use something like this to build a report that gives details for last month only.
Select [columns]
from [source]
where [Createdate] between
/*First day of last Month*/
DATEADD(mm, DATEDIFF(mm, 0, Getdate())-1, 0 and
/*First day of this Month*/
dateadd(mm,datediff(mm,0,Getdate()),0)

Related

How do I get the number of days in a month for the specific date in that row of data using SQL?

For example, if I have a data set including two columns, one which shows the month as a number and the other which shows the year (result of grouping my data using GROUP BY), I want to add another column called 'Days in the month' which will display the number of days in the respective month. Is there a way I can do this? Is there some function I can add in the SELECT clause?
I want to do this since there are further calculations I need to do with that number for each row.
In SQL Server 2012+, you can use:
select day(eomonth(datecol))
eomonth() gets the last day of the month. day() just returns the day of the month -- the number of days in the month, in this case.
For older SQL Server versions, I use the following:
DAY(DATEADD(MONTH, DATEDIFF(MONTH, -1, date_column)- 1, -1))
Much less elegant than the previous answer, but functional.

Calculating orders placed on the end of the month

I'm currently studying SQL Server using the book Ben-Gan, Itzik. T-SQL Fundamentals. Below is a query used to select order placed at end of the month. (I know that function EOMONTH() can also be used)
SELECT orderid, orderdate, custid, empid
FROM Sales.Orders
WHERE orderdate = DATEADD( month, DATEDIFF( month, '18991231', orderdate), '18991231');
The author's explanation is:
This expression first calculates the difference in terms of whole
months between an anchor last day of some month (December 31, 1899, in
this case) and the specified date. Call this difference diff. By
adding diff months to the anchor date, you get the last day of the
target month.
However, I'm still a bit confused as to how it actually works. Would someone kindly explain it?
That seems like a rather arcane way to do this. What the code is doing is calculating the number of months since the last day of some month. Then, it adds this number of months to that date. Because of the rules of dateadd(), the month remains the last date.
However, I prefer a simpler method:
where day(dateadd(day, 1, orderdate)) = 1
I find this much clearer.
select DATEDIFF(MONTH, '20160131', '20160201')
give us 1 month and
SELECT DATEADD(month, 1, '20160131')
give us 2016-02-29 00:00:00.000
that's ok
I tried out the query myself and seem to have got the hang of it. here is what i wrote just in case anyone else is interested
SELECT DATEADD(month, DATEDIFF(MONTH, '20160131', '20160201'), '20160131');
result:
2016-02-29 00:00:00.000
so my interpretation is that adding one or more "month" to a particular date in which the last date of the month is 31 will always return a date in which the date is the last day of the month. if this sentence makes any sense...

How to subtract one month from a Date Column

I know about Dateadd and datediff, but I cannot find any information how to use these functions on an actual date column rather than something like today's date with SQL Server.
Say I have the following Column
Dated
06/30/2015
07/31/2015
Now I want to add the following derived column that subtracts one month from every row in the Dated column.
Dated Subtracted
06/30/2015 05/31/2015
07/31/2015 06/30/2015
Thank you
The short answer: I suspect this is what you want:
dateadd(day, -datepart(day, Dated), Dated)
However, if you want "regular" subtract one month behavior in tandem with sticking to the end of month, having June 30 fall back to May 31 is slightly trickier. There's a discrepancy between the title or your question and the example where it appears you want the final day of month to stay anchored. It would be helpful for you to clarify this.
dateadd(month, -1, ...) doesn't handle that when the previous month has more days than the starting month although it works the other way around. If that's truly what you need I think this should handle it:
case
when datediff(month, Dated, dateadd(day, 1, Dated)) = 1
then dateadd(day, -datepart(day, Dated), Dated)
else dateadd(month, -1, Dated)
end
There's also a flavor of several date functions in that expression and a sense of how this date stuff can get complicated. The condition in the when looks to see if Dated is the last day of the month by checking that the following day is in a different calendar month. If so we extract the day of month and subtract that many days to jump back to the last day of the previous month. (Months start at one not zero. So for example, counting backward 17 days from the 17th lands in the month before.) Otherwise it uses regular dateadd(month, -1, ...) calculations to jump backward to the same day of month.
Of course if all your dates fall on the end of the month then this simple version will be adequate by itself because it always returns the last day of the previous month (regardless of where it falls in the starting month):
dateadd(day, -datepart(day, Dated), Dated) /* refer back to the top */
dateadd(day, -day(Dated), Dated) /* same thing */
And just for fun and practice with date expressions, another approach is that you could start on a known month with 31 days and calculate relative to that:
dateadd(month, datediff(month, '20151231', Dated) - 1, '20151231')
This finds the number of months between your date and a reference date. It works for all dates since it doesn't matter whether the difference is positive or negative. So then subtracting one from that difference and adding that many months to the reference point is the result you want.
People will come up with some pretty crazy stuff and I'm often amazed (for differing reasons) at some of the variations I see. chancrovsky's answer is a good example for closer examination:
dateadd(month, datediff(month, -1, Dated) - 1, -1)
It relies on the fact that date -1, when treated as implicitly converted to datetime, is the day before January 1, 1900, which does happen to be a month of 31 days as required. (Note that the - 1 in the middle is regular arithmetic and not a date value.) I think most people would advise you to be careful with that one as I'm not sure that it is guaranteed to be portable when Microsoft deprecates features in the future.
Why don't you just get the last day of the previous month? If this solve your problem, here's the sql server syntax, just replace the variable #yourDate with your column name.
DECLARE #yourDate DATE = '20160229'
select DATEADD(MONTH, DATEDIFF(MONTH, -1, #yourDate)-1, -1)
This also works if you're looking to find dates exactly 6 months behind.
Example:
DATEADD(DAY, DATEDIFF(DAY, -1, dates)-184, -31)

I want to find first day and any other in a month in SQL query

I want to find first day month of month and also like 3rd day or 5th day ,15th day or any day of the month .So how to find through query.I know how to find first day and last day of month.Mainy I want find other days.
For those of you following along who may not know how to get the First Day of the month in SQL Server you can do so with something like this. This will also give you the 5th, 10th or whatever you need.
DECLARE #FirstDay DATETIME
SET #FirstDay = (DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()) - 1, -1) + 1)
SELECT GETDATE() AS CurrentDay
, #FirstDay AS FirstDay
, DATEADD(d, 10, #FirstDay-1) AS TenthDay
The -1 after the #FirstDay in the DateAdd is because the DateAdd will add the numbers of days onto the firstday, which will give you the 11th in that example. Of course you could just add one less day to make it work without the -1 but I prefer including it. Suit yourself.
If you know how to find the first day of a month, you can add the 2-day, the 4-day or the 14-day interval to the first day of the month to get, respectively, the 3rd, the 5th or the 15th day of the month.
Similarly you can get any day of the month by simply adding the proper number of days.
Different RDBMSs may offer different syntax to achieve the goal. Assuming #MonthBeginning to be a date or datetime value representing the first day of a month, here's how you can get, for example, the 5th day of the same month in Microsoft SQL Server:
SELECT DATEADD(day, 4, #MonthBeginning) AS FifthDay
Again, it may not be the way you should do that if your RDBMS is not MS SQL Server.

SQL Select data by this week

Hi how do I get the data by current week?
Select * from Transaction where transactionDate ....
In SQL Server based on week of year. Please see DATEPART for ##DATEFIRST etc. for example, this is all trades since Sunday in US/UK settigs:
WHERE DATEPART(week, transactionDate) = DATEPART(week, GETDATE())
Edit:
For Access, use this DatePart and use "ww" for the part of date you want.
In answer to the comment, "week" is not a variable; it's the bit of the date you want
So:
WHERE DatePart("ww", transactionDate) = DatePart("ww", GETDATE())
In Microsoft Access
Last n days:
SELECT *
FROM Transaction
WHERE transactionDate >=Date()-7
If you have indexes and this type of difference suits, it will be faster because it is sargable
This week by week difference:
SELECT *
FROM Transaction
WHERE DateDiff("w",[transactionDate],Date())=0
BTW It is considered bad practice to use *
DateDiff: http://office.microsoft.com/en-us/access/ha012288111033.aspx
Simple but portable:
SELECT *
FROM Transaction
WHERE transactionDate >= ?
AND transactionDate <= ?
Calculate the two parameters in your server-side code to whatever definition of 'week' you need.
In IBM DB2
SELECT *
FROM Transaction
WHERE transactionDate BETWEEN CURRENT TIMESTAMP - 7 days AND CURRENT TIMESTAMP;
In Access, if you want to run a query to find records that fall in the current week, use
SELECT *
FROM table
WHERE table.DateField Between (Date()-Weekday(Date())+1) And (Date()-Weekday(Date())+7);
That runs Sunday through Saturday. Use +2 and +6 instead if you want the workweek.
mySQL (standard date stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(transactionDate);
mySQL (unix timestamp stamp)
SELECT *
FROM Transaction
WHERE WEEK(NOW())=WEEK(FROM_UNIXTIME(transactionDate));
Bit of a unoptimized query. Could be a more efficient way.
Note: This isn't a rolling 7 days. Just the current week of the year.
EDIT: Sorry I didn't see the ms-access tag. ignore all of this :|