您的位置:首页 > 数据库

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

2011-10-26 21:40 489 查看
数据操作中涉及到统计的部分主要借助数据库内置函数完成

SQL查询今天的记录:

datediff(day,[Datetime],getdate())=0 把Datetime换为你的相应字段;

SQL查询昨天的记录:

datediff(day,[Datetime],getdate())=1 把Datetime换为你的相应字段,getdate()-Datetime即为时间差。

本月记录:

SELECT * FROM 表 WHERE datediff(month,[dateadd],getdate())=0

本周记录:

SELECT * FROM 表 WHERE datediff(week,[dateadd],getdate())=0

本日记录:

SELECT * FROM 表 WHERE datediff(day,[dateadd],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 [Id]
,[Consume]--decimal
,[Date] --datatime
FROM [Coder].[dbo].[ConsumeRecord]


统计函数

--按日
select sum(consume),day([date]) from consumerecord where year([date]) = '2013' group by day([date])

--按周quarter
SET  DATEFIRST  1 --Sets the first day of the week to a number from 1 through 7
select sum(consume),datename(week,[date]) from consumerecord where year([date]) = '2013'
group by datename(week,[date])

--按月
select sum(consume),month([date]) from consumerecord where year([date]) = '2013' group by month([date])

--按季
select sum(consume),datename(quarter,[date]) from consumerecord where year([date]) = '2013' group by datename(quarter,[date])


tips

To see the current setting of SET DATEFIRST, use the @@DATEFIRST function.

参考

/article/5770771.html

http://msdn.microsoft.com/en-us/library/ms181598.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: