日期:2014-05-18 浏览次数:20571 次
;with ach as ( select dateadd(dd,number,cast(ltrim(year(getdate()))+'-01-01' as datetime)) date from master..spt_values where [type] = 'p' and number between 0 and 400 ),cte as ( select * from ach where year(date) = year(getdate()) ) select datepart(wk,date) as wk,min(date) mindate,max(date) maxdate from cte group by datepart(wk,date) /******************** wk mindate maxdate ----------- ----------------------- ----------------------- 1 2012-01-01 00:00:00.000 2012-01-07 00:00:00.000 2 2012-01-08 00:00:00.000 2012-01-14 00:00:00.000 3 2012-01-15 00:00:00.000 2012-01-21 00:00:00.000 4 2012-01-22 00:00:00.000 2012-01-28 00:00:00.000 5 2012-01-29 00:00:00.000 2012-02-04 00:00:00.000 6 2012-02-05 00:00:00.000 2012-02-11 00:00:00.000 7 2012-02-12 00:00:00.000 2012-02-18 00:00:00.000 8 2012-02-19 00:00:00.000 2012-02-25 00:00:00.000 9 2012-02-26 00:00:00.000 2012-03-03 00:00:00.000 10 2012-03-04 00:00:00.000 2012-03-10 00:00:00.000 11 2012-03-11 00:00:00.000 2012-03-17 00:00:00.000 12 2012-03-18 00:00:00.000 2012-03-24 00:00:00.000 13 2012-03-25 00:00:00.000 2012-03-31 00:00:00.000 14 2012-04-01 00:00:00.000 2012-04-07 00:00:00.000 15 2012-04-08 00:00:00.000 2012-04-14 00:00:00.000 16 2012-04-15 00:00:00.000 2012-04-21 00:00:00.000 17 2012-04-22 00:00:00.000 2012-04-28 00:00:00.000 18 2012-04-29 00:00:00.000 2012-05-05 00:00:00.000 19 2012-05-06 00:00:00.000 2012-05-12 00:00:00.000 ...
------解决方案--------------------
有函数的,自己拿去改一下
SQL季度函数
SELECT DATEPART(quarter,GETDATE()) --获取当前季度
这个季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)
上个季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-1, 0)
上上个季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-2, 0)
上上上个季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-3, 0)
......
n个季度前的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-n, 0)
这个季度的最后一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())+1, -1)
上个季度的最后一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), -1)
上上个季度的最后一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-1, -1)
n个季度前的最后一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate())-n+1, -1)
一个月第一天的SQL 脚本:
SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
本周的星期一
SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)
一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)
季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)
当天的半夜
SELECT DATEADD(dd, DATEDIFF(dd,0,getdate()), 0)
上个月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))
去年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))
本月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))
本年的最后一天