zoukankan      html  css  js  c++  java
  • sql server 简单语句整合

    1.去重distinct , group by

    select distinct userid,username from 表名
    select userid,username from 表名 group by userid,username


    2.去空格 replace  ltrim rtrim

    Replace(name,' ','')
    select ltrim('  test  ')        --去除左边的空格  
    select rtrim('  test  ')        --去除右边的空格  
    select ltrim(rtrim('  test  ')) --去除首尾空格  

    3.表表关联语句  where条件关联、左/右关联

    --用select更出要显示的字段
    select b.ID,GID,GName,GStand,GInPrice,GOutPrice,GBaseClass,b_Date,b_OPerson,b_Time
    --来自给tbl_Goods表和tbl_SellBill表,给tbl_Goods表设置一个别名a,给tbl_SellBill表设置一个别名b
    from tbl_Goods a,tbl_SellBill b
    --两个表关联的条件是 a.id=b.gid
    where a.id=b.gid
    select * from tableA a left  join  tableB b on a.id = b.id
    select * from tableA a right join  tableB b on a.id = b.id
    select * from tableA a inner join  tableB b on a.id = b.id
    left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 
    right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录
    inner join(等值连接) 只返回两个表中联结字段相等的行

    4.求比计算机系中某一学生年龄小的其他系的学生(any)

    方法一:
    select * 
    from student 
    where
        sdept!="CS" AND  
        sage < ANY (select Sage from Student where Sdept="CS");
        
    方法二:
    select  *
    from Student
    where   
       Sdept!=’CS’ AND  
       Sage < (select MAX(Sage) from Student where Sdept="CS");

    5.多重句子

    Teacher(tno, tname, salary, dno)
    Department(dno, dname)
    
    查询语句:
    select Tname,Salary
    from Teacher
    where 
        Dno = "D01" AND 
        salary IN(
            select salary from  teacher
            where Dno =select DNO from department where  Dname="国贸")
        );

    6.带有exists的相关子查询

    不相关子查询:    
    select Sname from student where sno IN ( select sno from SC where Cno = "C1" );
     
    相关子查询
    select Sname from student
    where exists (select * from SC where student.sno=SC.sno AND Cno = "C1" );

     7.交,并,差 

    1 Union 取合集并过滤重复数据

    --1 Union 取合集并过滤重复数据  
    --结果显示: 1,2,3,4,5  
    SELECT * FROM A  
    UNION     
    SELECT * FROM B;  

    2 Union all 取合集不过滤重复数据

    --2 Union all 取合集不过滤重复数据  
    --结果显示:1,2,3,4,1,2,5  
    SELECT * FROM A  
    UNION  all  
    SELECT * FROM B;  

    3 Intersect 取交集(两个表中都有数据)

    --3 Intersect 取交集  
    --结果显示:1,2  
    SELECT * FROM A  
    Intersect    
    SELECT * FROM B;  

    4 except 取差集(取A-B的记录)

    --4 except 取差集  
    --结果显示:3,4  
    SELECT * FROM A  
    except    
    SELECT * FROM B;  

     

  • 相关阅读:
    xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!
    win10右键新建markdown文件
    force down pool_member
    自控力差,你可能忽略了一种更底层的能力
    多线程的通信问题
    多线程的安全问题
    Java实现多线程的两种方式
    为什么你成不了数据分析高手?可能是缺少这个思维
    jstack && jmap
    对ElasticSearch主副分片的理解
  • 原文地址:https://www.cnblogs.com/hanke123/p/6397029.html
Copyright © 2011-2022 走看看