本来想偷懒 google 一下,没有满意的结果,好像他自己也没底!思路也不一样! 《求一尖酸的算法》(有点儿同感,说起来简单,做起来就晕) http://www.itpub.net/252645.html
顺便说一下,我写程序总想写的"更通用"一些,可能答非所问了!
由于 @@datefirst 可通过 set datefirst n 设定 导致 datepart(weekday,[date]) 不确定! 所以用 datename! 因为确定的日期是周几肯定是永远不变的!当然不随 datefirst 变! 所以更要用 datename! 另外按着中国人的习惯: 周日算作上周的最后一天! 如果是其他语言版本的 sql server 注意选用该语言版本的 周几 的形式!
declare @b datetime declare @e datetime
set @b = '2004-07-29' set @e = '2004-08-05'
select @b as 开始日期,@e as 结束日期, datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1 as 跨周数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期二','星期三','星期四','星期五','星期六','星期日') then 1 else 0 end as 周一个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期三','星期四','星期五','星期六','星期日') then 1 else 0 end - case when datename(weekday,@e) in ('星期一') then 1 else 0 end as 周二个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期四','星期五','星期六','星期日') then 1 else 0 end - case when datename(weekday,@e) in ('星期一','星期二') then 1 else 0 end as 周三个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期五','星期六','星期日') then 1 else 0 end - case when datename(weekday,@e) in ('星期一','星期二','星期三') then 1 else 0 end as 周四个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期六','星期日') then 1 else 0 end - case when datename(weekday,@e) in ('星期一','星期二','星期三','星期四') then 1 else 0 end as 周五个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@b) in ('星期日') then 1 else 0 end - case when datename(weekday,@e) in ('星期一','星期二','星期三','星期四','星期五') then 1 else 0 end as 周六个数
,datediff(week ,case when datename(weekday,@b) = '星期日' then @b - 1 else @b end ,case when datename(weekday,@e) = '星期日' then @e - 1 else @e end ) + 1
- case when datename(weekday,@e) in ('星期一','星期二','星期三','星期四','星期五','星期六') then 1 else 0 end