SQL

返回两个时间之间日期to_days函数  datediff函数

select to_days(now())-to_days(20190706) from dual;

select datediff(now(),'20190706')  from dual;

查询数据库昨天和今天的数据sql:
select * from 表名 where to_days(now())-to_days(时间字段名)<=1

查询昨天数据:
select * from 表名 where diffdate(字段,now())=-1


近七天数据(近多少天同理)
select * from 表名 where date_sub(curdate(),interval 7 day)<=date(时间字段名)


查看本月数据
select * from 表名 where data_format(时间字段名,'%Y%m')=date_format(curdate(),'%Y%m') ;

日期转时间戳
select UNIX_TIMESTAMP(sysdate()) from dual

时间戳转日期
select FROM_UNIXTIME(1562656158,'%Y/%m/%d %H:%i:%S') from dual

sql语句训练:
有学生表   
create table Students(Sid varchar(6), Sname varchar(10), Sage datetime, Ssex varchar(10));
分数表 
create table SC(Sid varchar(10), Cid varchar(10), score decimal(18,1));
课程表   
create table Course(Cid varchar(10),Cname varchar(10),Tid varchar(10));
教师表
create table Teacher(Tid varchar(10),Tname varchar(10));

1 查询出学生1号课程比2号课程分数高的学生信息

select s.*, a.score,b.score from students s,
(select sid,score from sc where cid='01')a,
(select sid,score from sc where cid='02')b 
where s.sid=a.sid and a.sid=b.sid and a.score>b.score


2.查询出平均分大于60的学生信息
select s.* ,avg(sc.score) avgs from student s,sc where s.sid=sc.sid group by sid having  avgs>60

3 查询所有同学的信息,选课总数,总成绩,没有则为null        (显示所有同学信息,则可以用left join)
select s.*,count(sc.cid),sum(sc.score) from students s 
left join sc on s.sid=sc.sid
group by sc.sid


4 查询学生信息,包括总分,单科分

select  s.*,sum(sc.score),
sum(case when cid=01 then score else null end  ) score01,
sum(case when cid=02 then score else null end  ) score02,
sum(case when cid=03 then score else null end  ) score03
from students s left join sc on s.sid=sc.sid
group by sid

sql练习例子

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值