一、运用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