时间:2021-07-01 10:21:17 帮助过:21人阅读
我现在有有一个表 主要字段有
time_id int
time_date datetime
year int
week_of_year int
day nvarhar
想要转换成另外一张表
time_id int
time_date datetime
year int
week_of_year nvarchar
原来的表内容是
--------------------
1 2003-07-09 2003 20 星期日
1 2003-07-10 2003 20 星期一
1 2003-07-11 2003 20 星期二
想要变成
--------------------
1 07/09/2003 2003 第20周(7/9-7/17)
1 07/10/2003 2003 第20周(7/9-7/17)
1 07/11/2003 2003 第20周(7/9-7/17)
请问:这个语句应该怎么去写?
答:
if object_id('tablename') is not null drop table tablename
select 1 as time_id, '2003-07-09' as time_date, 2003 as [year], 20 as week_of_year, '星期日' as [day]
into tablename
union select 1, '2003-07-10', 2003, 20, '星期一'
union select 1, '2003-07-11', 2003, 20, '星期二'
------------------------------------------------
select time_id, time_date, [year], '第' + cast(week_of_year as varchar(2)) + '周('
+ cast(month(week_begin) as varchar(2)) + '/' + cast(day(week_begin) as varchar(2)) + '-'
+ cast(month(week_end) as varchar(2)) + '/' + cast(day(week_end) as varchar(2)) as week_of_year
from (select *, dateadd(day, 1 - datepart(weekday, time_date), time_date) as week_begin,
dateadd(day, 7 - datepart(weekday, time_date), time_date) as week_end from tablename) a
/*
time_id time_date year week_of_year
1 2003-07-09 2003 第20周(7/6-7/12)
1 2003-07-10 2003 第20周(7/6-7/12)
1 2003-07-11 2003 第20周(7/6-7/12)
*/
------------------------------------------------
drop table tablename
问题虽然解决了,但这个例子并不具备通用性,还是个案,所以我们分析了你的代码,发现一个问题:日期范围是如何确定的?所以,我们把它延伸发散到:能否自主设定日期的范围呢?比如设定到星期一或星期天开始:
思路:
SET DATEFIRST
将一周的第一天设置为从 1 到 7 之间的一个数字。
语法
SET DATEFIRST { number | @number_var }
参数
number | @number_var
是一个整数,表示一周的第一天,可以是下列值中的一个。