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


    数据操作中涉及到统计的部分主要借助数据库内置函数完成

    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.

    参考 

    http://www.cnblogs.com/aijun/archive/2011/03/18/1987750.html

    http://msdn.microsoft.com/en-us/library/ms181598.aspx

  • 相关阅读:
    算法的时间复杂度与空间复杂度
    递归八皇后问题(回溯算法)
    vue之插件
    递归之打印、阶乘、九九乘法表、迷宫问题
    选择排序
    归并排序
    sql 字符保留汉字处理
    JAVA filter map groupingBy Collectors
    2021最新版IDEA激活
    WPF 程序退出,进程依然存在
  • 原文地址:https://www.cnblogs.com/needrunning/p/2225715.html
Copyright © 2020-2023  润新知