dateadd(mm, DATEPART(MONTH, DATE) - 1, 0) + DATEPART(DAY, DATE) - 1
OUTPUT date is in the year for example 1990-12-02 00:00:00:000
Full query is below:
SELECT dateadd(yy, (
DATEPART(YEAR, GETDATE()) + (
CASE
WHEN DATEPART(MONTH, GP_DATE) > 10
THEN 0
ELSE 1
END
) - 1900
), 0) + dateadd(mm, DATEPART(MONTH, GP_DATE) - 1, 0) + DATEPART(DAY, GP_DATE) - 1 GP_DATE
from table
I am trying to convert this query into snowflake syntax and snowflake syntax dateadd function does not allow 1, 0.
In SQL Server, there are some rather ugly implicit conversions available between datetimes and integers.
0, when converted to a date, becomes 1900-01-01.
You're also allowed to do maths on dates. Adding or subtracting 1 adds or subtracts 1 day from the date. Putting these facts together, we have:
dateadd(yy, (
DATEPART(YEAR, GETDATE()) + (
CASE
WHEN DATEPART(MONTH, GP_DATE) > 10
THEN 0
ELSE 1
END
) - 1900
), 0)
Which is taking the current year, and subtracting 1900 from it (or 1899 if the month is less than 11, for whatever reason). We then take that number and add it back to the date 0 (which as stated above is 1900-01-01). The result is that we get the first of January of next year or this year, depending on the month of GP_DATE. Call this D1.
Moving on:
dateadd(mm, DATEPART(MONTH, GP_DATE) - 1, 0)
is taking the month of GP_DATE, subtracting 1 from it and adding that number of months to the date 0 (1900-01-01). The result is a the 1st of whichever month GP_DATE is in, but in 1900. Let's call this D2.
When we add D1 and D2 together, we approximately get a date of the 1st of whichever month GP_DATE is in, in either this year or next year. Note, however, that this goes wrong if the D1 year is a leap year, we get it wrong by a day for months after February.
Finally, we take DATEPART(DAY, GP_DATE) - 1, where we take the day of the month from GP_DATE, subtract 1, and add that on to our result so far. This should set the final date to be on the same day of the month as GP_DATE, except for the error mentioned above.
So, it appears that the code is trying to take GP_DATE and get the same date in either this year or next year, depending on how late in the year GP_DATE is. However, it also appears it was never tested with consideration for leap years.
A far more likely correct version of this query would be this instead:
SELECT
DATEADD(year,
DATEDIFF(year,GP_DATE,CURRENT_TIMESTAMP) +
CASE WHEN DATEPART(month,GP_DATE)>10 THEN 0 ELSE 1 END
,GP_DATE)
Related
I'm using SSMS/SSRS2012 working on report to capture all hours worked in the current fiscal year, which for this purpose is Oct 1-Sep 30.
I'm looking for a case statement that says the following:
if the current month < 10 (october) then #FYStart = last year
if the current month >= 10 then #FYStart = current year
When I query SELECT GETDATE() here is the format: 2020-06-16 15:24:57.637
I have tried the following, but it only half works.
SELECT CASE WHEN DATEPART(MONTH,(CAST(getdate() AS INT)))>09
THEN YEAR(CAST(getdate() AS INT))
ELSE DATEADD(YEAR,-1,(CAST(getdate() AS INT)))
END
The result from this gives me 2019-06-17 00:00:00.000 which is a step in the right direction, but if I change the month to a month that has already passed,
SELECT CASE WHEN DATEPART(MONTH,(CAST(getdate() AS INT)))>03
THEN YEAR(CAST(getdate() AS INT))
ELSE DATEADD(YEAR,-1,(CAST(getdate() AS INT)))
END
I get this result: 1905-07-14 00:00:00.000
Something is obviously going wrong here but I'm not sure what exactly. I'm thinking it's something with the data types but I'm not sure what to check/where to start.
So from what I gather, you are trying to isolate the year (as an integer) from today's date and store it in #FYStart. If today's date is before October, you want to assign it to last year, and if it's October or later, assign it to this year, correct?
If so, try this:
DECLARE #FYStart int
SET #FYStart = (
SELECT CASE WHEN DATEPART(MONTH, GETDATE()) < 10
THEN DATEPART(YEAR, DATEADD(YEAR, -1, GETDATE())) -- last year
ELSE DATEPART(YEAR, GETDATE()) -- this year
END
)
Unless I'm overlooking something, is it not just something as simple as...
SELECT CASE WHEN MONTH(getdate()) <10
THEN YEAR(getdate()) -1
ELSE YEAR(getdate())
END
If applied to today, I want to return values for 1/10/19 through 25/02/20.
I am using the below currently, but wish to replace it with something that gives me 4 complete months and the current partial month
where DATEDIFF (day,[SubOrderCompletionDate],GETDATE()) between 0 and 180
Thanks
If you want complete months, just change this to:
where DATEDIFF(month, SubOrderCompletionDate, GETDATE()) between 0 and 3
DATEDIFF() counts the number of boundaries between two dates. So, all days within a given calendar month return the same value.
I've taken your statement literally, and therefore assumed that if today was 29 February 2020 you would want 1 November 2019 to 29 February 2020, not 1 October 2019 to 29 Feburary 2020:
SELECT * --This should be a column list, not *
FROM dbo.YourTable YT
WHERE YT.SubOrderCompletionDate >= CASE WHEN EOMONTH(GETDATE()) = CONVERT(date,GETDATE()) THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 3,0) ELSE DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 4,0) END
AND YT.SubOrderCompletionDate <= GETDATE()
If that isn't the case, you just need DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 4,0), which will give you 5 months worth of data.
For the below query
Sum(CASE WHEN dbo.sales.date BETWEEN '2016-07-17' AND '2016-07-23' THEN dbo.sales.sellinc END) AS ActualSales
Instead of hard coding the date. I would like to pick current date from machine and compare
Sum(CASE WHEN dbo.sales.date BETWEEN '**previous week (31 week 2016)**' AND '**Last year same week (31 week 2015)**' THEN dbo.sales.sellinc END) AS ActualSales
Week start from Sunday and ends Saturday. Any help please?
I think this snippet might help you to get a range of one year from the previous week to last year.
Sum(CASE
WHEN dbo.sales.date
BETWEEN DATEADD(YEAR, -1, DATEADD(WEEK, -1, GETDATE())) AND
DATEADD(WEEK, -1, GETDATE()) THEN dbo.sales.sellinc END) AS ActualSales
You can also modify the logic if you want to consider Friday as an exception.
In that case, you have to use DATEPART(WEEKDAY, GETDATE()) function to get the week day which returns 1 for Sunday and 7 for Saturday. It would be prettier if you move the date generation logic to a variable and then use it to select your data.
Others have already noted that your method of week numbering is going to impact your solution. Here's one that just looks for the Sunday of the current week and then subtracts 52 weeks. (You could also just deduct 364 days in the previous step and use dateadd only once.) So the correspondence with the previous year's week is essentially the nearest calendar date falling on Sunday that year.
with dates as (
select
dateadd(week, -52,
dateadd(day,
1 - datepart(weekday, getdate()), /* Sunday of current week */
cast(getdate() as date)
)
) as WeekStartY-1,
dateadd(day, 1 - datepart(weekday, cast(getdate() as date)) as WeekStartY-0
)
select
sum(case when cast(s."date" as date)
between d.WeekStartY-0 and dateadd(day, 6, WeekStartY-0) then s.sellinc end
) as ActualSalesY-0,
sum(case when cast(s."date" as date)
between d.WeekStartY-1 and dateadd(day, 6, WeekStartY-1) then s.sellinc end
) as ActualSalesY-1,
from dbo.Sales s cross apply dates d;
This can occasionally produce an oddity where the weeks both start in the same year. It happens when the year ends on Sunday, or Monday in leap years, as with 2012. So Y-1 for December 30, 2012 was January 1, 2012. But consider that most of the days for that week actually fall in 2013 and the correspondence makes sense from that perspective.
You can try using DATEADD:
SUM(CASE WHEN dbo.sales.date BETWEEN DATEADD(week, 30, '2016/01/01') AND
DATEADD(week, 30, '2015/01/01')
THEN dbo.sales.sellinc END) AS ActualSales
This will give you the one year range between the 30th week of 2015 and 2016, using the SQL Server week, whose first week begins on January 1st, regardless of the day. If you really want to use the ISO week, then it will be a lot more work.
I'm hoping to find a solution for this to automate a report I have. Basically what I'm trying to accomplish here is grabbing a date (first day of previous month, two years ago through last day of previous month current year).
So the date span if running this month would look like this: between 4/1/2013 and 3/31/2015
I have found code to get the date two years ago but I'm not able to also incorporate the month functions... Any help is very much appreciated!
For year I'm using this:
SELECT CONVERT(VARCHAR(25),DATEADD(year,-2,GETDATE()),101)
First day of previous month 2 years ago:
SELECT CONVERT(DATE,dateadd(day, -1, dateadd(day, 1 - day(GETDATE()), GETDATE())))
Last day of last month:
SELECT CONVERT(DATE,DATEADD(month, DATEDIFF(month, 0, DATEADD(year,-2,GETDATE())), 0))
Then just do whatever logic you need with them
Your where clause can look something like this:
where date >= cast(dateadd(year, -2,
dateadd(month, -1, getdate() - day(getdate()) + 1)
) as date) and
date < cast(getdate() - day(getdate()) + 1 as date)
This makes use of the handy convenience that subtracting/adding a number to a datetime is the same as adding a date. The start date says: get the first day of the month, then subtract one month, then subtract two years. This could have been done as dateadd(month, -25, . . .), but I think separating the logic is clearer.
This gives you two dates you are looking for:
SELECT
CAST((DATEADD(yy, -2, DATEADD(d, -1 * DATEPART(dd, getdate()) + 1 , GETDATE() ))) as date) as yourTwoYearsAgoDate,
CAST((DATEADD(d, -1 * DATEPART(dd, GETDATE()), GETDATE())) as date) as yourEndOfLastMonthDate
Given a reference date (e.g. "today"),
declare #today date = '23 April 2015'
The 1st of the month is computed by subtracting 1 less than the day number of the current month:
select first_of_current_month = dateadd(day,1-day(#today),#today)
The last day of the previous month is day 0 of the current month, so to get the last day of the previous month, just subtract the current day number:
select last_of_previous_month = dateadd(day,-day(#today),#today)
Moving two years back is easy:
select two_years_back = dateadd(year,-2, #today )
Putting it all together, this should do you:
declare #today date = '23 April 2015'
select *
first_day_of_current_month = dateadd(day,1-day(#today),#today),
last_day_of_previous_month = dateadd(day, -day(#today),#today) ,
date_from = dateadd(year,-2, dateadd(day,1-day(#today),#today) ) ,
date_thru = dateadd(day, -day(#today),#today)
yielding the expected results:
first_day_of_current_month: 2015-04-01
last_day_of_previous_month: 2015-03-31
date_from : 2013-04-01
date_thru : 2015-03-31
So you should be able to say something like this:
select *
from foo t
where t.transaction_date between dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and dateadd(day, -day(#today),#today)
If you have to deal with datetime values rather than date, its easier to not use between and say something like this:
declare #today date = current_timestamp -- get the current date without a time component
select *
from foo t
where t.transaction_date >= dateadd(year,-2, dateadd(day,1-day(#today),#today) )
and t.transaction_date < dateadd(year, 0, dateadd(day, -day(#today),#today)
[superfluous addition of 0 years added for clarity]
Specifically MSSQL 2005.
Here's a solution that gives you the last second of the current month. You can extract the date part or modify it to return just the day. I tested this on SQL Server 2005.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
To understand how it works we have to look at the dateadd() and datediff() functions.
DATEADD(datepart, number, date)
DATEDIFF(datepart, startdate, enddate)
If you run just the most inner call to datediff(), you get the current month number since timestamp 0.
select datediff(m, 0, getdate() );
1327
The next part adds that number of months plus 1 to the 0 timestamp, giving you the starting point of the next calendar month.
select dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 );
2010-09-01 00:00:00.000
Finally, the outer dateadd() just subtracts one second from the beginning timestamp of next month, giving you the last second of the current month.
select dateadd( s, -1, dateadd( mm, datediff( m, 0, getdate() ) + 1, 0 ) );
2010-08-31 23:59:59.000
This old answer (below) has a bug where it doesn't work on the last day of a month that has more days than the next month. I'm leaving it here as a warning to others.
Add one month to the current date, and then subtract the value returned by the DAY function applied to the current date using the functions DAY and DATEADD.
dateadd(day, -day(getdate()), dateadd(month, 1, getdate()))
SELECT DATEADD(M, DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), '1990-01-31T00:00:00.000')
Explanation:
General approach: use temporal functionality.
SELECT '1990-01-01T00:00:00.000', '1990-01-31T00:00:00.000'
These are DATETIME literals, being the first time granule on the first day and last day respectively of the same 31-day month. Which month is chosen is entirely arbitrary.
SELECT DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP)
This is the difference in whole months between the first day of the reference month and the current timestamp. Let's call this #calc.
SELECT DATEADD(M, #calc, '1990-01-31T00:00:00.000')
This adds #calc month granules to the last day of the reference month, the result of which is the current timestamp 'rounded' to the last day of its month. Q.E. D.
Try this:
DATEADD (DAY, -1, DATEADD (MONTH, DATEDIFF (MONTH, 0, CURRENT_TIMESTAMP) + 1, 0)
They key points are if you can get first day of current month,Last Day of Last Month and Last Day of Current Month.
Below is the Step by Step way to write query:
In SQL Server Date Starts from 1901/01/01( Date 0) and up to now each month can be identified by a number. Month 12 is first month of 1902 means January. Month 1200 is January of 2001. Similarly each day can be assigned by unique number e.g Date 0 is 1901/01/01. Date 31 is 1901/02/01 as January of 1901 starts from 0.
To find out First day of Current Month(Current Date or a given date)
First we need to check how many months have passed since date 0(1901/01/01).
SELECT DATEDIFF(MM,0,GETDATE())
Add same number of month to date 0(1901/01/01)
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0)
Then we will get first day of current month(Current Date or a given date)
To get Last Day of Last Month
We need to subtract a second from first day of current month
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE()),0))
To get Last Day of Current Month
To get first day of current month first we checked how many months have been passed since date 0(1901/01/01). If we add another month with the total months since date 0 and then add total months with date 0, we will get first day of next month.
SELECT DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0)
If we get first day of next month then to get last day of current month, all we need to subtract a second.
SELECT DATEADD(SS,-1,DATEADD(MM, DATEDIFF(MM,0,GETDATE())+1,0))
Hope that would help.
Using SQL2005, you do not have access to a helpful function EOMONTH(), So you must calculate this yourself.
This simple function will works similar to EOMONTH
CREATE FUNCTION dbo.endofmonth(#date DATETIME= NULL)
RETURNS DATETIME
BEGIN
RETURN DATEADD(DD, -1, DATEADD(MM, +1, DATEADD(DD, 1 - DATEPART(DD, ISNULL(#date,GETDATE())), ISNULL(#date,GETDATE()))))
END
Query to perform:
SELECT dbo.endofmonth(DEFAULT) --Current month-end date
SELECT dbo.endofmonth('02/25/2012') --User-defined month-end date
Some links to possible answers:
http://www.extremeexperts.com/sql/Tips/DateTrick.aspx
http://www.devx.com/tips/Tip/14405
http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html
DECLARE
#Now datetime,
#Today datetime,
#ThisMonth datetime,
#NextMonth datetime,
#LastDayThisMonth datetime
SET #Now = getdate()
SET #Today = DateAdd(dd, DateDiff(dd, 0, #Now), 0)
SET #ThisMonth = DateAdd(mm, DateDiff(mm, 0, #Now), 0)
SET #NextMonth = DateAdd(mm, 1, #ThisMonth)
SET #LastDayThisMonth = DateAdd(dd, -1, #NextMonth)
Sometimes you really do need the last day of this month, but frequently what you really want is to describe the time interval of this month. This is the best way to describe the time interval of this month:
WHERE #ThisMonth <= someDate and someDate < #NextMonth
For completeness, in Oracle you'd do something like ...
select add_months(trunc(sysdate,'MM'),1) ...
or
select last_day(sysdate)+1 ...
DATEADD(dd, -1, DATEADD(mm, +1, DATEADD(dd, 1 - DATEPART(dd, #myDate), #myDate)))