Sql Server date query - SQL query today, yesterday, within 7 days, 30 days (transfer)

All data of today: select * from table name where DateDiff(dd, datetime type field, getdate()) = 0 
All data of yesterday: select * from table name where DateDiff(dd, datetime type field, getdate()) = 1 
All data within 7 days: select * from table name where DateDiff(dd, datetime type field, getdate())<= 7 
All data within 30 days: select * from table name where DateDiff(dd, datetime type field, getdate() )<= 30 
All data of this month: select * from table name where DateDiff(mm, datetime type field, getdate())=0 
All data of this year: select * from table name where DateDiff(yy, datetime type field, getdate()) = 0
 
 
Query today is the day of the year: select datepart(dayofyear,getDate())
Query today is the day of the month: 1 . select datepart(dd, getDate()) 
                         2 . select day(getDate())
Query the Monday date of this week (Note: the specified date cannot be Sunday, if it is Sunday, it will be calculated to the next Monday. So if it is Sunday, one day will be subtracted) SELECT DATEADD(wk,DATEDIFF(wk, 0 , getdate()), 0 )
 
Query yesterday's date: select convert( char ,dateadd(DD,- 1 ,getdate()), 111 )   // 111 is the style number, (100-114) 
 
query the date of the first day of the month: Select DATEADD(mm, DATEDIFF( mm, 0 ,getdate()), 0 ) as firstday
Query the date of the last day of the month: Select dateadd(ms, - 3 ,DATEADD(mm, DATEDIFF(m, 0 ,getdate())+ 1 , 0 )) as lastday       // Modifying  
the value of -3 will have corresponding changes 
How many days are there in a month: select datepart(dd,dateadd(dd,- 1 ,dateadd(mm, 1 ,cast((cast(year(getdate()) as varchar)+ ' - ' +cast(month(getdate()) as varchar)+ ' -01 ' ) as datetime ))))
 
Find the difference in days between two time periods: select datediff(day, ' 2012/8/1 ' , ' 2012/8/20 ' ) as daysum
±N days on the specified date: select convert( char ,dateadd(dd, 1 , ' 2012/8/20 ' ), 111 ) as riqi     // Output 2012/8/21 
±N minutes on the specified date: select dateadd(mi,- 15 ,getdate())   // Query the date 15 minutes before the current time

 

Original address: https://www.cnblogs.com/suruozhong/p/5974595.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325027137&siteId=291194637