How can I get the date of the first second of the year with SQL? - sql

I'm working on a purging procedure on SQL Server 2005 which has to delete all rows in a table older than 1 year ago + time passed in the current year.
Ex: If I execute the procedure today 6-10-2009 it has to delete rows older than 2008-01-01 00:00 (that is 2007 included and backwards).
How can I get the date of the first second of the year?
I've tried this:
select cast((DATEPART(year, getdate()) -1 )AS DATETIME);
but I get 1905-07-02 00:00:00.000 and not 2008-01-01 00:00 (as I wrongly expected).
Can someone help me, please?

EDIT: This was returning current year, when the question was for previous year. Code has been corrected to reflect this.
use this
select DATEADD(yy, DATEADD(yy, DATEDIFF(yy,0,getdate()), 0), -1)
OR to use your variable:
select DATEADD(yy, DATEADD(yy, DATEDIFF(yy,0,#YourDateTimeValue), 0), -1)

This will work:
select cast('01 jan' + CAST((DATEPART(year, getdate())-1) as varchar) AS DATETIME);
(I know it's not the "best" solution and probably involves more casts than necessary, but it works, and for how this will be used it seems to be a pragmatic solution!)

SELECT DATEADD(year, DATEDIFF(year, 365, GETDATE()), 0)

Related

sql server dateadd() using column name year and not keyword 'year'

I am using DATEADD(year, -3, GETDATE()) to pull the last thee years worth of data on a rolling period.
I also have a column called Year, the view I am creating is using the MyTable.Year and not the sql keyword 'year'.
e.g DATEADD(MyTable.year, -3, GETDATE())
It resolves it every time in the view which is really annoying. I'm a bit rusty, been out of this for about 4 years.
How do I make sure it uses the keyword 'year', I find it strange it is doing this. Any explanation on this would also be helpful. SQL Server 2016
Thanks guys.
EDIT: I have edited my misplaced schema notation and identified the table name, sorry for confusion
I am not sure if I understand correctly, but you want to enforce the keyword, so you want to subtract 3 years from the current date, correct? This should work:
SELECT DATEADD(yy, -3, GETDATE())
or
SELECT DATEADD(yyyy, -3, GETDATE())
(unless you have columns named yy and yyyy ;-))
Otherwise forgive my misunderstanding...
It seems your editor has problems with the keyword YEAR and replaces it with a value from a column that is also called year
This can be solved by using a synonym for the keyword year in the DateAdd function.
So instead of
dateadd(year, -3, getdate())
use
dateadd(yy, -3, getdate())
You could put your table in a subquery and alias [Year] column.
Something like
SELECT ... FROM (SELECT [Year] AS "MyYear" FROM ...) X
(or use CTE)
Then Year would only mean the keyword.

SQL find out how many days into year date is

I want to work out an annual figure as a proportion of the year based on the date - so if 400 is the annual figure, I want to divide this by 365 then multiply the result by however many days is equivalent to today's date (e.g. (400/365)*160)).
Is there a way of doing this with a SQL server select statement to avoid manually entering the 160 figure?
The 400 figure is coming from a standard field named HES.
Thanks.
You can use datepart(dayofyear, getdate()) - will return a number representing today's day of the year. See MSDN DatePart
Since this is sql server and the other answer is using mysql I will post the sql server version.
select DATEPART(dayofyear, getdate())
For your calculation, you might want to take leap years into account. SQL Server has a convenient datepart(dayofyear, . . ) functionality. The complete solution would look like:
select datepart(dayofyear, dateadd(day, -1, cast(cast(year(getdate() + 1) as varchar(255)) + '0101' as date))) as daysinyear,
datepart(dayofyear, getdate()) as currentday,
datepart(dayofyear, getdate()) * 1.0 / datepart(dayofyear, dateadd(day, -1, cast(cast(year(getdate() + 1) as varchar(255)) + '0101' as date)))as daysinyear
Note that SQL Server does integer division, so to get a fraction, you need to convert to a decimal representation of some sort (* 1.0 is just a simple way of doing this).

SQL Server : select count of Todays Transactions

I was wondering if someone could help me as I can't seem to find an answer to the following that I have been searching for.
Select
Count(pm1.number) As number
From
SCenter.probsummarym1 As pm1
Where
pm1.open_time >= Today()
I have the above that works great if I put in the date as '01-05-2015'
But I want today's date each day when it refreshes.
Sorry if this is pretty basic but I am just lost on this one
GETDATE() will return the current date and time.
You may then use a CAST() or CONVERT() to strip the time value and be left with just the date, ie.
SELECT CONVERT(VARCHAR(10), GETDATE(), 110)
The above code would return 05-19-2015 for today.
Select
Count(pm1.number) As number
From SCenter.probsummarym1 As pm1
Where
pm1.open_time >= GETDATE() //or CONVERT(VARCHAR(10), GETDATE(), 110)

SQL for last six "full" months

I have table containing one datetime column. I need to return rows for only last 6 months. This can be done by
WHERE CloseTime >= DATEADD(Month, DATEDIFF(Month, 0, DATEADD(m, - 6, CURRENT_TIMESTAMP)), 0)
This gets me data for the month I am starting this script + 6 last months. So e.g. if I run this script today, Ill get the data for this month + all previous months till April (04).
Now I need to modify the condition so if I run the script today, the data will be obtained only for months 03-09 only, exluding days in this month (10).
Any advice, please?
If you want to have the previous 6 months regardless of whether today is the 1st, 3rd, 9th, 29th, whatever, then just subtract 7 months. Here is one way to do that: get the first of the month into a variable, then use an open-ended range in the query.
DECLARE #ThisMonth DATETIME;
SET #ThisMonth = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
SELECT...
WHERE CloseTime >= DATEADD(MONTH, -7, #ThisMonth)
AND CloseTime < #ThisMonth;
You could also use 0 in place of '19000101' but I prefer an explicit date than implicit shorthand (it was a very tough habit to break).
If you really don't like variables, then you can make the query a lot more complex by repeating the expression to calculate the first of this month (and in the start of the range, subtract 7 from the number of months):
SELECT...
WHERE CloseTime >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CloseTime < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101');
Yuck. Variables make this much tidier.
When creating queries you do not want to use a function on the search column since it will result in a full table scan.
The solution works and should pick up any index on CloseTime.
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
CloseTime between
DATEADD(d, -1, '03-01-2013') and DATEADD(d, +1, '09-20-2013')
If the table is small and a full table scan is not a issue, a simple solution is to use the MONTH function.
-- Get me data in months 3 (mar) to 9 (sep) of this year
select
*
from
my_table
where
MONTH(CloseTime) IN (3,4,5,6,7,8,9) and YEAR(CloseTime) = 2013
I looked at Aaron's article. Its a very good read.
I wondered if there was some new function that was not tested since that article.
If you are using 2012, why not use the format function? Logically, you want date variables with a 01 day. The query plan still gets a clustered index scan.
Let's see how this solution stacks up using Aaron's test database.
-- Use the sample
use [DateTesting]
go
-- Johns - log by 6 months
CREATE PROCEDURE dbo.Johns_LogBy6Months
#date SMALLDATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmp_date SMALLDATETIME = format(#date, 'yyyyMM01');
DECLARE #c INT;
SELECT #c = COUNT(*)
FROM dbo.SomeLogTable
WHERE DateColumn >= dateadd(m, -7, #cmp_date)
AND DateColumn < #cmp_date
END
GO
-- Aarons - log by 6 months
CREATE PROCEDURE dbo.Aarons_LogBy6Months
#date SMALLDATETIME
AS
BEGIN
SET NOCOUNT ON;
DECLARE #c INT;
DECLARE #cmp_date SMALLDATETIME = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', #date), '19000101');
SELECT #c = COUNT(*)
FROM dbo.SomeLogTable
WHERE
DateColumn >= dateadd(m, -7, #cmp_date)
AND DateColumn < #cmp_date
END
GO
Lets make 1000 calls to the functions.
-- Sample calls x 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
EXEC dbo.Johns_LogCountByDay #date = '20091005';
GO 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
EXEC dbo.Aarons_LogBy6Months #date = '20091005';
GO 1000
PRINT CONVERT(char(23), GETDATE(), 121);
GO
Here are the executions times.
2013-10-10 11:58:49.547
Beginning execution loop
Batch execution completed 1000 times.
2013-10-10 11:58:52.837
Beginning execution loop
Batch execution completed 1000 times.
2013-10-10 11:58:55.883
In summary a call to the new format() function and a implicit cast to a small date time takes a little more time than a dateadd() and datediff() with two string (date) literals.
The format() solution seems more intuitive or self documenting to me. The time difference was 3.3 versus 3.0 sec.
I have to give the speed test a win to Aaron's solution. Stick with in-equality comparisons of date variables. They are faster.
In short, I will have to fix my bad habits.
I had a similar request. I needed last six months and next six months of appointments. But just like you I needed the full months. So a simple getdate +- 180 wouldn't do.
I took a more simple approach. I get the year and month and turn it into a number like 201912. Then do a between clause. Its dynamic and I get full months.
I'm sure there's more sophisticated approaches, but this is what I came up with.
WHERE Year([ApptDate])*100 + Month([ApptDate]) between Year(getdate()-180)*100 + Month(getdate()-180) and Year(getdate()+180)*100 + Month(getdate()+180)

SQL Server: Get data for only the past year

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?
SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'
The following adds -1 years to the current date:
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
Then if you want to restrict this query, you can add some other filter, but always searching in the last year.
SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
The most readable, IMO:
SELECT * FROM TABLE WHERE Date >
DATEADD(yy, -1, CONVERT(datetime, CONVERT(varchar, GETDATE(), 101)))
Which:
Gets now's datetime GETDATE() = #8/27/2008 10:23am#
Converts to a string with format 101 CONVERT(varchar, #8/27/2008 10:23am#, 101) = '8/27/2007'
Converts to a datetime CONVERT(datetime, '8/27/2007') = #8/27/2008 12:00AM#
Subtracts 1 year DATEADD(yy, -1, #8/27/2008 12:00AM#) = #8/27/2007 12:00AM#
There's variants with DATEDIFF and DATEADD to get you midnight of today, but they tend to be rather obtuse (though slightly better on performance - not that you'd notice compared to the reads required to fetch the data).
Look up dateadd in BOL
dateadd(yy,-1,getdate())
GETDATE() returns current date and time.
If last year starts in midnight of current day last year (like in original example) you should use something like:
DECLARE #start datetime
SET #start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) -- getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
SELECT column1, column2, ..., columnN FROM table WHERE date >= #start
I, like #D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. #samjudson's answer provides that. #D.E. White's answer returns results for the prior calendar year.
My query is a bit different in that it works for the prior year up to and including the current date:
SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))
For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017
For some reason none of the results above worked for me.
This selects the last 365 days.
SELECT ... From ... WHERE date BETWEEN CURDATE() - INTERVAL 1 YEAR AND CURDATE()
The other suggestions are good if you have "SQL only".
However I suggest, that - if possible - you calculate the date in your program and insert it as string in the SQL query.
At least for for big tables (i.e. several million rows, maybe combined with joins) that will give you a considerable speed improvement as the optimizer can work with that much better.
argument for DATEADD function :
DATEADD (*datepart* , *number* , *date* )
datepart can be: yy, qq, mm, dy, dd, wk, dw, hh, mi, ss, ms
number is an expression that can be resolved to an int that is added to a datepart of date
date is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value.
declare #iMonth int
declare #sYear varchar(4)
declare #sMonth varchar(2)
set #iMonth = 0
while #iMonth > -12
begin
set #sYear = year(DATEADD(month,#iMonth,GETDATE()))
set #sMonth = right('0'+cast(month(DATEADD(month,#iMonth,GETDATE())) as varchar(2)),2)
select #sYear + #sMonth
set #iMonth = #iMonth - 1
end
I had a similar problem but the previous coder only provided the date in mm-yyyy format. My solution is simple but might prove helpful to some (I also wanted to be sure beginning and ending spaces were eliminated):
SELECT ... FROM ....WHERE
CONVERT(datetime,REPLACE(LEFT(LTRIM([MoYr]),2),'-
','')+'/01/'+RIGHT(RTRIM([MoYr]),4)) >= DATEADD(year,-1,GETDATE())
Here's my version.
YEAR(NOW())- 1
Example:
YEAR(c.contractDate) = YEAR(NOW())- 1
For me this worked well
SELECT DATE_ADD(Now(),INTERVAL -2 YEAR);
If you are trying to calculate "rolling" days, you can simplify it by using:
Select ... FROM ... WHERE [DATE] > (GETDATE()-[# of Days])