Convert Quarter + Year to a date - sql

I have two fields I need to combine and convert to a date. These two fields are i) Quarter &
ii) Year
For example Q2 2017
01/04/2018
I don't have a field for the day so I just want to keep it to the first of the month.
Please could someone help with the SQL. I need to add to a select statement.

In Microsoft SQL Server you can do this as followed:
First I create a date as varchar which I then convert to the Date datatype. After this I format it to the desired format. I use a CASE Clause to get the correct month by the quarter.
SELECT FORMAT(CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
CAST(CASE
WHEN [Quarter] = 'Q1' THEN '01'
WHEN [Quarter] = 'Q2' THEN '04'
WHEN [Quarter] = 'Q3' THEN '07'
WHEN [Quarter] = 'Q4' THEN '10' END AS VARCHAR(2))+'-'+
CAST('01' AS VARCHAR(2))), 'dd-MM-yyyy', 'en-us')
from dates

If you are using SQL SERVER , then you can try something like this:
SELECT
CONCAT(Quarter,
CONVERT(date, DATEADD(MONTH, DATEDIFF(MONTH, 0, year), 0))) AS StartOfMonth
FROM Table1;
If you need some space in between Quarter and Year then, add ' '.
SELECT
CONCAT(Quarter,' ',
CONVERT(date, DATEADD(MONTH, DATEDIFF(MONTH, 0, year), 0))) AS StartOfMonth
FROM Table1;

Related

SQL CASE rolling date difference

How would I pull the annual rolling date difference within a case statement? Or, if there's a better method that would work. When the NXT Anniversary Date month is after the current month, then I need the date to roll to the next year. I need to see the next anniversary dates that would be coming up in 2022.
For example:
Below is the code I was using, which works great for the current year.
Declare #prevbiz as Date set #prevbiz = DateAdd(day,Case (Datepart(Weekday,Cast(GetDate() as Date)))
When 2 then -3
Else -1
End, Cast(GetDate() as Date));
DECLARE #prev12MONTHS AS DATE set #prev12MONTHS = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 12, DAY(#enddate)-1)
SELECT
ANNUALREVIEWDATE
, 'NXT Anniversary Date' = CASE WHEN DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz), ANNUALREVIEWDATE) <= #prev12MONTHS
THEN DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz) -1, ANNUALREVIEWDATE)
ELSE DATEADD(yy, DATEDIFF(yy, ANNUALREVIEWDATE, #prevbiz), ANNUALREVIEWDATE)
END
FROM [table]
I believe you're just looking to decide whether the anniversary has already passed and should then be advanced to next year.
datefromparts(
year(getdate()) +
case when datefromparts(2000, month(getdate()), day(getdate()))
>= datefromparts(2000, month(X), day(X))
then 1 else 0 end,
month(getdate()),
day(getdate())
)
You could also just compare month and day parts individually. Year 2000 is just an arbitrary year that happens to have a leap day.
Based on my findings on your question, this maybe could help you.
with dates(annualAnniversary) as (
select DateAdd(month,6,DateAdd(year,-5,cast(GetDate() as date)))
union
select DateAdd(month,3,DateAdd(year,-4,cast(GetDate() as date)))
union
select DateAdd(month,3,DateAdd(year,-1,cast(GetDate() as date)))
union
select DateAdd(month,5,DateAdd(year,-2,cast(GetDate() as date)))
union
select DateAdd(month,2,DateAdd(year,-1,cast(GetDate() as date)))
union
select DateAdd(month,8,DateAdd(year,-3,cast(GetDate() as date)))
union
select DateAdd(month,0,DateAdd(year,0,cast(GetDate() as date)))
)
select annualAnniversary,
DateAdd(year,DATEDIFF(year,annualAnniversary, cast(GetDate() as date)),annualAnniversary) as needsToShow
from dates
for excluding rows those not meet their own annual Anniversary, You can add this to the above code:
where DATEDIFF(year,annualAnniversary, cast(GetDate() as date))>0
Output with raw data:

If/Then/Else in Formatting a Date

I am trying to get the fiscal period and year out of an invoice date. Using the month() function together with the Case I am able to get the period. since Period 1 is in November I need to do a +1 1 the year when this is true
Using the IF function together with the date functions are now working for me.
My query is
Select a.OrderAccount
,a.InvoiceAccount
,a.InvoiceDate
,year(a.InvoiceDate) as Year
,month(a.InvoiceDate) as Month,
Case month(a.InvoiceDate)
WHEN '11' THEN '1' -- increase year by +1
WHEN '12' THEN '2'-- increase year by +1
WHEN '1' THEN '3'
WHEN '2' THEN '4'
WHEN '3' THEN '5'
Any advice would be appreciated. Thanks
Use DATEADD to just add 2 months to the original date:
MONTH(DATEADD(month,2,a.InvoiceDate)) as FiscalMonth,
YEAR(DATEADD(month,2,a.InvoiceDate)) AS FiscalYear,
Create and populate a Calendar Table (it makes working with dates much easier).
create table Calendar
(
id int primary key identity,
[date] datetime,
[day] as datepart(day, [date]) persisted,
[month] as datepart(month, [date]) persisted,
[year] as datepart(year, [date]) persisted,
day_of_year as datepart(dayofyear, [date]) persisted,
[week] as datepart(week, [date]),
day_name as datename(dw, [date]),
is_weekend as case when datepart(dw, [date]) = 7 or datepart(dw, [date]) = 1 then 1 else 0 end,
[quarter] as datepart(quarter, [date]) persisted
--etc...
)
--populate the calendar
declare #date datetime
set #date = '1-1-2000'
while #date <= '12-31-2100'
begin
insert Calendar select #date
set #date = dateadd(day, 1, #date)
end
Then, create a FiscalYear view:
create view FiscalYear
as
select
id,
case when month = 11 or month = 12 then year + 1 else year end as [year]
from Calendar
So, whenever you need the fiscal year of a given date, just use something like the following query:
select C.*, FY.year fiscal_year from Calendar C inner join FiscalYear FY on FY.id = C.id
Of course, since fiscal year is just a computation on a column, you could also just make it a part of the calendar table itself. Then, it's simply:
select * from Calendar
If you want to stick with arithmetic: The fiscal month is ( Month( a.InvoiceDate ) + 1 ) % 12 + 1 and the value to add to the calendar year to get the fiscal year is Month( a.InvoiceDate ) / 11.
The following code demonstrates 12 months:
with Months as (
select 1 as M
union all
select M + 1
from Months
where M < 12 )
select M, ( M + 1 ) % 12 + 1 as FM, M / 11 as FYOffset
from Months;
D Stanley's answer makes your intention clearer, always a consideration for maintainability.
If you have this logic in 10 different places and the logic changes starting (say) on 1/1/2018 you will have a mess on your hands.
Create a function that has the logic and then use the function like:
SELECT InvoiceDate, dbo.FiscalPeriod(InvoiceDate) AS FP
FROM ...
Something like:
CREATE FUNCTION dbo.FiscalPeriod(#InvoiceDate DateTime)
RETURNS int
AS BEGIN
DECLARE #FiscalDate DateTime
SET #FiscalDate = DATEADD(month, 2, #InvoiceDate)
RETURN YEAR(#FiscalDate) * 100 + MONTH(#FiscalDate)
END
This returns values like 201705, but you could have dbo.FiscalPeriodMonth() and dbo.FiscalPeriodYear() if you needed. And you can have as complicated logic as you need in one place.

Replace the date value to first of the month if it is any other day

I have a requirement for a date column.
Condition: If the date column value is any date other then the 1st of its month then the same has to be replaced to 1st of that month, say for example today its 05-01-2017 and it has to be replaced by 01-01-2017. Similarly for 15th of the month.
I have achieved the same using below query:
select 'date column',
case when datediff(DAY,-15, 'date column') != 41043 then
DATEADD(dd,-(DAY( 'date column')-1), 'date column')
end
from TABLE
This I cracked by running below query:
select datediff(DAY,-15,'date column')
from TABLE
This gives value "41043", which I used in my query.
But I have two concerns here
what is this value "41043" ?? like is it ASCII value of that date or subtraction of date from SQL beginning date ..etc..
Is there any other Simpler way to achieve my query?
Please suggest.
There is also an easier way without using CASE, you can always add 16 days (for 31 days months) then found first day of the month like this:
SELECT
DATEADD(month, DATEDIFF(month, 0, DATEADD(DAY, 16, dateColumn)), 0) AS firstDayOfMonth
FROM
yourTable;
SELECT
'date column'
,CASE
WHEN DATEPART(DAY, 'date column') < 15 THEN
CONVERT(VARCHAR(10), DATEADD(mm, DATEDIFF(mm, 0, 'date column'), 0), 105)
WHEN DATEPART(DAY, 'date column') >= 15 THEN
CONVERT(VARCHAR(10), DATEADD(mm, DATEDIFF(mm, 0, 'date column'), 14), 105)
END
FROM
[TABLE]

Year Calculation in SQL Server 2012

StartDate = 01/01/2013
EndDate = 12/31/2019
I need to get the year column like '2013-14' , '2014-15' , 2015-16 and so on.
For example, the 2013-14 year should contains date details from Jun 2013 to May 2014. Like wise i need to get the year upto End date. Please help me out.
concat(datepart(YY,StartDate ),'-', RIGHT(YEAR(StartDate ),2) + 1)
I used the above format. i can get the output as 2013-14. But i need to specify the range of month for splitting years.
Regards,
Vanmathi
Use the FORMAT function:
SELECT
FORMAT(StartDate, 'yyyy-MM'),
FORMAT(EndDate, 'yyyy-MM')
Read all about the FORMAT function on the official MSDN documentation page.
Use a user defined function to slice up the date and then text concatenation.
CREATE FUNCTION GetSlicedYear(#TheDate date)
RETURNS varchar(7)
AS
BEGIN
DECLARE #SlicedYear varchar(7)
IF DATEPART(month, #TheDate) < 6
SELECT #SlicedYear = (DATEPART(year, #TheDate) -1 ) +"-"+ RIGHT(CAST(YEAR(#TheDate) As varchar(4)),2)
ELSE
SELECT #SlicedYear = DATEPART(year, #TheDate) +"-"+ RIGHT(CAST((YEAR(#TheDate) +1) As varchar(4)),2)
RETURN #SlicedYear
END
Then something like this to Order (or group).
SELECT SomeField, GetSlicedYear(SomeDate) FROM SomeTable ORDER BY GetSlicedYear(SomeDate)
You can use the below select statement -
select FORMAT(StartDate , 'yyyy') + '-' + FORMAT(EndDate , 'yyyy')

How can I use GETDATE() to get month and year from the past month?

How can I get it to one statement that can get me
last month and this year?
I have a INSERT INTO and in a column report_date [datetime]
insert into table_a (report_date) values ( ??);
i want to show this past month and year,
So for example today is 4/21/2014
so it would show 3/2014 in the column
If today was MAY 1 2014 , it would show 4/2014?
Is this possible or does it have to have a day?
You're looking for the DATEADD function:
SELECT DATEPART(month, DATEADD(month, -1, GETDATE()), DATEPART(year, DATEADD(month, -1, GETDATE())
If you are trying to get 'last month' with 'this year' you could do:
SELECT CAST(
CAST(YEAR(GETDATE()) AS VARCHAR) + '-' +
CAST(MONTH(GETDATE())-1 AS VARCHAR) + '-' +
CAST(DAY(GETDATE()) AS VARCHAR)
AS DATETIME)
But then in JAN 2015, it would return DEC 2015.
If you just want last month, use the 'DATEADD' function.
SELECT DATEADD(MONTH, -1, GETDATE())