SQL Server獲取本月上月本週等函式用法
SQL Server DATEDIFF() 函式----(返回兩個日期之間的時間):
SQL Server DATEADD() 函式----(在日期中新增或減去指定的時間間隔)
語法:DATEADD(datepart,number,date)
學習 : month(create_day)=month(getdate())本月 month(create_day)=month(getdate())-1 上月
--本月 select count(*) from User where datepart(mm,create_day) = datepart(mm,getdate())
--上月 select count(*) from User where datepart(mm,create_day) = datepart(mm,getdate()) - 1
--求兩個時間相差天數 select datediff(day,'2004-01-01',getdate()) --本週 select count(*) from User where datediff(dd,create_day,getdate()) <= datepart(dw,getdate()) --上週 select count(*) from User where datediff(dd,create_day,(getdate() - datepart(dw,getdate()))) <= 7 --1.一個月第一天 SELECT dateadd(mm, DATEDIFF(mm,0,getdate()), 0) --2.本週的星期一 SELECT dateadd(wk, DATEDIFF(wk,0,getdate()), 0) select dateadd(wk,datediff(wk,0,getdate()),6) --一年的第一天 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(mm,0,getdate())+1, 0)) --本年的最後一天 SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0)) --本月的第一個星期一 select DATEADD(wk, DATEDIFF(wk,0,dateadd(dd,6-datepart(day,getdate()),getdate())), 0)--查詢本週註冊人數 --上週註冊人數 select count(*) from [user] where datediff(week,create_day-1,getdate())=1 --獲取本月資訊 select * from user where datediff(month,create_day,getdate())=0 --獲取上月資訊 select * from user where datediff(month,create_day,getdate())=1 --如果要效率,這樣寫查詢 --查詢本週註冊人數 select * from user where create_day>=dateadd(day,2-datepart(weekday,getdate()),convert(varchar,getdate(),112)) and create_day<dateadd(day,9-datepart(weekday,getdate()),convert(varchar,getdate(),112)) --上週註冊人數 select * from user where create_day>=dateadd(day,-5-datepart(weekday,getdate()),convert(varchar,getdate(),112)) and create_day<dateadd(day,2-datepart(weekday,getdate()),convert(varchar,getdate(),112)) --本月註冊人數 select * from user where create_day>=dateadd(day,1-day(getdate()),convert(varchar,getdate(),112)) and create_day<dateadd(month,1,dateadd(day,1-day(getdate()),convert(varchar,getdate(),112))) --上月註冊人數 select * from user where create_day>=dateadd(month,-1,dateadd(day,1-day(getdate()),convert(varchar,getdate(),112))) and create_day<dateadd(day,1-day(getdate()),convert(varchar,getdate(),112))
--今日記錄 SELECT * from feedback WHERE (DATEDIFF(d,fedtime,GETDATE())=0) ORDER BY fedid DESC