Home > Database > Mysql Tutorial > body text

初学者必读:精讲SQL中的时间计算语句_MySQL

WBOY
Release: 2016-06-01 14:00:08
Original
927 people have browsed it

问:请问,如何计算一个表中的周起始和截止日期并写到表字段中? 我要从一个表向另一个表导入数据,并进行转换,用的是VB 。

我现在有有一个表 主要字段有

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

是一个整数,表示一周的第一天,可以是下列值中的一个。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!