獲取時間差的sql語句

 

"select count(*) from [註冊] where datediff(day,time,getdate())<1";//獲取當天註冊人員數
sql="select id,classid,classname,xiaoshoue,xiaoshou,jinhuo,kucun,addtime "
sql=sql&" from xiaoshou where addtime between '" & format(starttime,"yyyy-mm-dd") & "' and '" & format(endtime,"yyyy-mm-dd") & "'"
sql=sql&" order by id desc"

Select Fylb,Pm,Gg,Dw,Dj,Sl,Je FROM cqyzypzx where zxdate between {^2003-7-1}and {^2003-8-1}

近兩個星期
sql="select * from table where datediff(week,riqi,getdate())<=2"

近三個月
sql="select * from table where datediff(month,riqi,getdate())<=3"

近一年
sql="select * from table where datediff(year,riqi,getdate())<=1"

Apply_Date between #"& startdate &" 23:59:59# and #"& enddate &" 23:59:59#" 

 

參考以下日期寫法
---求相差天數
select datediff(day,'2004-01-01',getdate())

SELECT DATEDIFF(day,'2008-12-29','2008-12-30') AS DiffDate

結果:

DiffDate
1

轉貼:
--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)
--3.一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

--4.季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

--5.當天的半夜
SELECT DATEADD(dd, DATEDIFF(dd,0,getdate()), 0)

--6.上個月的最後一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))

--7.去年的最後一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

--8.本月的最後一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))

--9.本年的最後一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))

--10.本月的第一個星期一
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())=0

--上週註冊人數
select count(*) from [user]
where datediff(week,create_day-1,getdate())=1


--本月註冊人數
select count(*) from [user]
where datediff(month,create_day,getdate())=0

--上月註冊人數
select count(*) from [user]
where datediff(month,create_day,getdate())=1

 

 

--如果要效率,這樣寫查詢

--查詢本週註冊人數
select count(*) 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 count(*) 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 count(*) 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 count(*) 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))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章