灰儿 发表于 2016-9-13 11:03:31

SQL查询今天与昨天的记录,及本月记录、本周记录

数据操作中涉及到统计的部分主要借助数据库内置函数完成SQL查询今天的记录:datediff(day,,getdate())=0把Datetime换为你的相应字段;SQL查询昨天的记录:datediff(day,,getdate())=1把Datetime换为你的相应字段,getdate()-Datetime即为时间差。 本月记录:SELECT * FROM 表 WHERE datediff(month,,getdate())=0 本周记录:SELECT * FROM 表 WHERE datediff(week,,getdate())=0 本日记录:SELECT * FROM 表 WHERE datediff(day,,getdate())=0


函数参数/功能
GetDate( )返回系统目前的日期与时间
DateDiff (interval,date1,date2)以interval 指定的方式,返回date2 与date1两个日期之间的差值 date2-date1
DateAdd (interval,number,date)以interval指定的方式,加上number之后的日期
DatePart (interval,date)返回日期date中,interval指定部分所对应的整数值
DateName (interval,date)返回日期date中,interval指定部分所对应的字符串名称
另外一种使用内置函数查询的方法测试表SELECT       ,--decimal      , --datatimeFROM ..
统计函数http://common.cnblogs.com/images/copycode.gif
--按日 select sum(consume),day() from consumerecord where year() = '2013' group by day() --按周quarterSETDATEFIRST1 --Sets the first day of the week to a number from 1 through 7select sum(consume),datename(week,) from consumerecord where year() = '2013' group by datename(week,) --按月 select sum(consume),month() from consumerecord where year() = '2013' group by month() --按季 select sum(consume),datename(quarter,) from consumerecord where year() = '2013' group by datename(quarter,) http://common.cnblogs.com/images/copycode.gif

tipsTo see the current setting of SET DATEFIRST, use the @@DATEFIRST function.参考 http://www.cnblogs.com/aijun/archive/2011/03/18/1987750.htmlhttp://msdn.microsoft.com/en-us/library/ms181598.aspx

页: [1]
查看完整版本: SQL查询今天与昨天的记录,及本月记录、本周记录