sqlserver the datepart and datediff applications to find data in the morning and afternoon

DATEPART () function returns separate portions date / time, such as year, month, day, hour, minute and so forth.

The DATEDIFF () function returns the time difference between the two dates.

- Find the morning's data 
 the SELECT  *  from R_Attendance the WHERE ( the datepart of a (hour, RDatetime) > = 0  and  the datepart of a (hour, RDatetime) < 12 ) and   DATEDIFF (d, RDatetime, GetDate ()) = 0  
 
- Find the afternoon data 
 SELECT  *  from R_Attendance WHERE ( the datepart (hour, RDatetime) > 12 is  and  the datepart (hour, RDatetime) <= 23 is ) and   DATEDIFF(d,RDatetime,GetDate())=0 

Calculating the difference between two time

A difference of a few years: SELECT DATEDIFF (YEAR, '2017-07-01 11:25:52', '2018-07-02 12:25:52'); Results: 1

Difference between the number of days: SELECT DATEDIFF (DAY, '2018-07-01 11:25:52', '2018-07-02 12:25:52'); Results: 1

Difference hours: SELECT DATEDIFF (HOUR, '2018-07-01 11:00:00', '2018-07-01 16:00:00'); Results: 5

A difference of scores: MINUTE, the number of seconds difference: SECOND, a difference of a few months: MONTH

Gets the day, month, and year data:

According to the above calculated time difference, we can obtain results as follows:

当日:SELECT * FROM UserTable WHERE DATEDIFF(DAY, StartTime, GETDATE())=0

当月:SELECT * FROM UserTable WHERE DATEDIFF(MONTH, StartTime, GETDATE())=0

当年:SELECT * FROM UserTable WHERE DATEDIFF(YEAR, StartTime, GETDATE())=0

If you want to get the previous day, month or year, etc., can function only equal to 1, and so can, on the contrary get a month later, and year. Function is equal to -1, not to list here.

Guess you like

Origin www.cnblogs.com/qinyi173/p/11416380.html