简体   繁体   English

在SQL上转换为ISO周到月的日期

[英]Conver to ISO week to month date on SQL

I've searched on almost every question but haven't come with what I need, so here it goes: 我已经搜索了几乎所有问题,但都没有提供我所需要的,所以就这样:

I need to convert a date in the format of 'yyyyww' (where 'ww' is the iso week of the year) to 'yyyymm' (where 'mm' is the month of the year). 我需要将“ yyyyww”(其中“ ww”是一年中的等周)格式的日期转换为“ yyyymm”(其中“ mm”是一年中的月份)。

So, for example, I have the date 201725 (which is year 2017, ISO week 25) to be displayed as 201706, since the ISO week 25 is on June of the same year. 因此,例如,我将日期201725(即2017年,ISO周25)显示为201706,因为ISO周25在同年6月。

Use a combination of the LEFT , CONVERT & DATEADD Functions. 结合使用LEFTCONVERTDATEADD函数。

SELECT LEFT(CONVERT(varchar, DATEADD(week, yourfield % 100 - 1, DATEADD(year, yourfield / 100 - 1900, 0)),112),6)
FROM yourtable

Input 输入

201722
201733
201725

Output 产量

201705
201708
201706

SQL Fiddle: http://sqlfiddle.com/#!6/00eaa/7/0 SQL小提琴: http ://sqlfiddle.com/#!6/00eaa/7/0

This is a bit strange for output because you can get the same value for more than 1 week but I will leave that up to you to sort out. 对于输出而言,这有点奇怪,因为您可以在1个星期以上的时间内获得相同的值,但我将根据您的选择进行排序。

This produces the desired output stated for the input provided. 这将为提供的输入产生所需的输出。

declare @YourValue varchar(10) = '201725'

select left(replace(convert(varchar(10), dateadd(week, convert(int, right(@YourValue, 2)), left(@YourValue, 4) + '0101'), 102), '.', ''), 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM