simple you can do this in one line:
select dat, concat(datediff(year,'1900-1-1',dat) /100,datediff(year,'1900-1-1',dat) % 100, datepart(DAYOFYEAR,dat) ) as JDE from d
I stored your example input data in a table call d under column dat:
dat JDE
---------- ------------------------------------
2017-07-27 117208
Explanation:
first it is important to understand what is JDE julian date. it is in this format CYYDDD:
- C stands for centuries and it starts at the 20th century (hence the hard coded date
1900-01-01
in my query). C is 0 if the years of 19xx. C is 1 for the years of 2000. This is why we took your date and get the number of different years since 1900-01-01 and divided it by 100 to get the number of centuries. datediff(year,'1900-1-1',dat) /100
- YY stands for the years in the century. so if the year is 2089 the first three digit of JDE would be 189DDD
datediff(year,'1900-1-1',dat) % 100
helps you get the remainder of the century which is the years.
- DDD is the day of the year. In sql server there is a very nice to get day of the year using
datepart(DAYOFYEAR,dat)
Now we get all three parts of JDE we concat()
them together and you have your JDE year.
EDIT:
I added some logic to ensure all fields would have proper 0 paddings.
SELECT dat ,CONCAT(RIGHT(CONVERT(varchar(1),datediff(year,'1900-1-1',dat) / 100),1) , RIGHT(CONVERT(varchar(2), datediff(year,'1900-1-1',dat) % 100),2), RIGHT('000' + CONVERT(varchar(3),datepart(DAYOFYEAR,dat)),3)) from d