zoukankan      html  css  js  c++  java
  • 常用SQL语句汇总整理_02

    1.SQL中的反转透视

     创建数据源: 

      创建表结构
      if OBJECT_ID('Score' ,'U') is not null
      drop table Score

      create table Score
      (
        学号 nvarchar(10),
        课程 nvarchar(10),
        成绩 int
      )

      insert into Score values('0001','语文',87);
      insert into Score values('0001','数学',79);
      insert into Score values('0001','英语',95);
      insert into Score values('0002','语文',69);
      insert into Score values('0002','数学',84);

    Method 1:

    select 学号,
    sum(case when 课程='语文' then 成绩 else 0 end) as 语文,
    sum(case when 课程='数学' then 成绩 else 0 end) as 数学,
    sum(case when 课程='英语' then 成绩 else 0 end) as 英语
    from Score
    group by 学号

    Method 2:

    select distinct 学号,
    max(case when 课程='语文' then 成绩 else 0 end) over(partition by 学号) as 语文,
    max(case when 课程='数学' then 成绩 else 0 end) over(partition by 学号) as 数学,
    max(case when 课程='英语' then 成绩 else 0 end) over(partition by 学号) as 英语
    from Score

    Method 3:

    select  学号,

    sum(case when 课程 = '语文' then 成绩 end) as 语文,

    sum(case when 课程 = '数学' then 成绩 end) as 数学,

    ISNULL(sum(case when 课程 = '英语' then 成绩 end),0) as 英语

    from  Score

    group by 学号

    2、批量更新操作

    update table1 set (table1.c1,table1.c2)=(select table2.c1,table2.c2 from table2 where table1.id=table2.id)

  • 相关阅读:
    搜索表头的例子-jqueryEasyUi
    Class^=,Class*= ,Class$=含义(转)
    js中slice方法(转)
    java中File的delete和deleteOnExit区别(转)
    BeanUtils.populate的方法的作用
    java NIO编程(转)
    java socket 之UDP编程
    彻底理解ThreadLocal(转)
    @RequestBody, @ResponseBody 注解详解(转)
    Spring MVC之@RequestMapping 详解
  • 原文地址:https://www.cnblogs.com/gotoschool/p/2960444.html
Copyright © 2011-2022 走看看