1. 程式人生 > >SQL查詢今天、昨天、7天內、30天

SQL查詢今天、昨天、7天內、30天

今天的所有資料:select * from 表名 where DateDiff(dd,datetime型別欄位,getdate())=0

昨天的所有資料:select * from 表名 where DateDiff(dd,datetime型別欄位,getdate())=1

7天內的所有資料:select * from 表名 where DateDiff(dd,datetime型別欄位,getdate())<=7

30天內的所有資料:select * from 表名 where DateDiff(dd,datetime型別欄位,getdate())<=30

本月的所有資料:select * from 表名

where DateDiff(mm,datetime型別欄位,getdate())=0

本年的所有資料:select * from 表名 where DateDiff(yy,datetime型別欄位,getdate())=0

查詢今天是今年的第幾天: select datepart(dayofyear,getDate())

查詢今天是本月的第幾天:1. select datepart(dd, getDate()) 

                                                2.select day(getDate())

查詢本週的星期一日期是多少 (注意:指定日期不能是週日,如果是週日會計算到下週一去。所以如果是週日要減一天)
SELECT DATEADD(wk,DATEDIFF(wk,0,getdate()),0)

查詢昨天日期:select convert(char,dateadd(DD,-1,getdate()),111)  //111是樣式號,(100-114)

查詢本月第一天日期:Select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) as firstday

查詢本月最後一天日期:Select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as lastday      //修改-3的值會有相應的變化

本月有多少天:select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast((cast(year(getdate()) as varchar)+'-'+cast(month(getdate()) as varchar)+'-01' ) as datetime ))))

求兩個時間段相差幾天:select datediff(day,'2012/8/1','2012/8/20') as daysum

在指定的日期上±N天:select convert(char,dateadd(dd,1,'2012/8/20'),111) as riqi    //輸出2012/8/21

在指定的日期上±N分鐘:select dateadd(mi,-15,getdate())  //查詢當前時間15分鐘之前的日期