SQL语句灵活运用

一、运用SQL语句查询一段时期内的数据
 方法1:
 DATEDIFF函数
 语法:

DATEDIFF(department, startdate, enddate)
1
DATEDIFF函数,主要作用于返回两个日期差的一个函数
department:一个参数,在SQL语句中位于DATEDIFF括号里的第一个参数位置,SQL语句中的dd,wk为department的缩写

        //查询当天的数据
        select sum(balance) from student_Info where DATEDIFF(dd, date, date)=0

        //查询近7天的数据
        select sum(addmoney) from ReCharge_Info where DATEDIFF(wk, date, date)<=7

        //查询近30天的数据
        select sum(addmoney) from ReCharge_Info where DATEDIFF(dd, date, date)<=30

        //查询昨天的数据
        select sum(addmoney) from ReCharge_Info where DATEDIFF(wk, date, date)=1

        //查询季度数据
        select sum(addmoney) from ReCharge_Info where DATEDIFF(qq, date, date)=0

        //查询一年的数据
        select sum(addmoney) from ReCharge_Info where DATEDIFF(yy, date, date)=0
 方法2:
 使用between
 between表示两者之间,查询结果更灵活,范围更广泛
 语法:

字段名 between startdate and enddate

 代码展示

//查询student_info表中balance列在一段时间范围内的总和
select sum(balance) from student_info where status=1 and ispay='未结账' and date between @date1 and @date2 
//sum:sql语句中求和函数,括号内为要求和的列。date为表中的日期列,@date1,@date2为U层给的具体日期,也可称为实参

二、运用SQL语句查询最新数据
方法1
查询最新日期,可查出最新最近生成的数据

select * from orderlist_info where cardid=@cardid and ispay='未付款' and date=(select max(date)from orderlist_info

方法二
查询最新时间的数据,用于数据生成日期相同,时间不同的情况

select * from orderlist_info where cardid=@cardid and ispay='未付款' and time=(select max(time)from orderlist_info

方法三
运用order by 排序,倒序查询,查询结果是最新最近的数据

select top 1 * from OrderList_info where cardid=123 and ispay='未付款'  order by id desc

三、SQL语句的计算类查询

总数:select count  from 表名
求和:select sum(列名) from 表名
平均:select avg(列名) from 表名
最大:select max(列名) from 表名
最小:select min(列名) from 表名

四、随机查询数据库中数据,随机生成随机数
 应用背景:查看客户的反馈意见与留言。

select top 1 * ,NEWID() as random from Ideas_Info where status='未处理' order by random 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值