SQL基本语法和实战经验

写了很多SQL了,现在拿出来,分享给大家,希望对大家有帮助。case when bug 修复:2018-05-23更

select * from tablename limit 10; 查看表内数据,一般为了便于查看,会限制数据数目,比如10;

desc tablename; 查看表字段名,字段类型,也比较常用;

select a.*,b.*  from  test_1 a  left out join  test_2 b on a.id=b.id  左连接;这个以test_1为主表,然后在test_2中,能够匹配到的id,会把相关字段,增加到test_1上,没匹配的字段,数据会以Null填充;无论什么join,如果有重复id,会实现多连接;

需求:将每个数据除以一列的总和,子查询方法,

select id,num/(select sum(num) from test_one) b) from test_one;

需求;从重复数据中找出显示一行数据:

select max(id),max(num) from test_one group by id;

case when 多条件选择:有时候判断要根据两个字段来写,所以又是case when了

select id,case when score>90 then case when num>5 then 'good' end as label ;分数>90,且有5门以上学科,评价为good;

跑一批业务数据,发现了一个小问题,一直在查sql逻辑,一点问题都没有,之前每段查,终于发现了这个case when的问题!

扫描二维码关注公众号,回复: 1853806 查看本文章

case when a<4  then 1 when 4<= a <8 then 2  这样能通过,但是结果是错的

更正方法:case when a<4  then 1 when a>=4  and a<8 then 2 这样是可以的

找出一组数据中最大,第二大,第三大数据:使用窗口函数,例如我们现在有id,num 两个字段

select id,num from(select id,num,row_number over(partition by id order by num desc) r from table)t where r=2,通过利用r的取值来取排序数据,

 


猜你喜欢

转载自blog.csdn.net/zehui6202/article/details/80038802