SQL语句总结(将平常用到的SQL语句总结)

本文深入探讨了SQL在数据处理中的高效应用,包括日期格式转换、字段截取、复杂查询及统计分析等实用技巧,旨在提升数据库操作技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、查找如 2018-07-08 19:20:30 中的年份

SELECT DATE_FORMAT(datetime,'%Y') FROM TestTable;

2、截取字段,截取年月日前面的年,但是必须把表中这个字段改为varchar,不能为datetime

UPDATE `table01` SET `datetime`=LEFT(`datetime`,4)

3、查询表中每年每个市的采购总金额

SELECT A.* FROM 
   (SELECT year AS year,
    area AS area,
    SUM(amountMoney) AS money
    FROM table01 GROUP BY year,area ORDER BY money DESC) A 

4、查询表中每年某个市的采购总金额

SELECT A.* FROM (
    SELECT year as year,
    area as area,
    SUM(amountMoney) as money
    from table01 group by year,area HAVING area='深圳市' order by money DESC
)A

5、查询表中某年某个市的采购总金额

select A.* from (select year as year,
    area as area,
    sum(amountMoney) as money,
    from table02 group by year,area having area='深圳市' and year='2019' order by DESC
)A

//或者直接写成下面这样
select year,city,sum(amountMoney) as money 
from table01 group by city,year having year=#{year} 
order by money desc

6、创建表

create table StudentScore (
    Code int(11) not null,
    Class varchar(50) not null,
    Score int(11) not null,
    primary key (Class)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;

7、删除表

drop table if exists StudentScore;

8、添加外键约束

alter table studentsocre 
    add constraint FK123 foreign key(Code) references student(Code);

9、查询学生信息表中,手机号码为空,或者以“138”开头的记录

select * from student where PhoneNumber is null or PhoneNumber like '138%'

10、求总分在150-200分之间的学生个数

select count(Code) from (select Code from StudentScore 
    group by Code having sum(Score) between 150 and 200) as a;

11、找出每门课都大于80分的学生姓名(约定每一个学生都有成绩记录)

select Name from Student a where not exists (
    select Distinct b.Code from StudentScore b where b.Score<=80 and a.Code=b.Code);

12、求没有参加“数据结构”课程考试的学生姓名列表

select Name from Student a where not exists (
    select * from StudentScore b where Class='数据结构' and a.Code=b.Code);

12、查找统计

如有表 temp,数据如下:

timeresult
2018-05-19success
2018-05-19success
2018-05-19fail
2018-05-19fail
2018-05-20success
2018-05-20fail
2018-05-20fail

需要查询得到如下结果:

timesuccessfail
2018-05-1922
2018-05-2012

sql语句可以如下写:

//方法一
select time,sum(case when result='success' then 1 else 0 end)'success',
            sum(case when result='fail' then 1 else 0 end)'fail' 
from temp group by time

//方法二
select s.time,s.success,f.failure from
(select time,count(*) as 'success' from temp where result='success' group by time)s,
(select time,count(*) as 'fail' from temp where result='fail' group by time)f
where s.time = f.time

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值