zoukankan      html  css  js  c++  java
  • 行转列

    给定一个数据库的表Test,表的内容如图所示。
    | id | class | score |
    | ------------- |:-------------:| -----:|
    | 1 | one | 91 |
    | 2 | one | 92 |
    | 3 | two | 93 |
    | 4 | two | 94 |

    要求写出一个SQL语句,得到如下的结果。

    one two
       2 2

    思路

    select class, count(*) from Test group by class

    得到

    one 2
    two 2

    再行转列

    with t1 as (
      select class, count(*) as num from Test group by class
    )

    select
    sum(case class when 'one'  then num else 0 end) as one,
    sum(case class when 'two'  then num else 0 end) as two
    from t1

    方法二:

    select
     sum(case class when 'one'  then 1 else 0 end) as one,
     sum(case class when 'two'  then 1 else 0 end) as two
    from Test

    方法三:

    SELECT * FROM
      (
            select class, count(*) as num from Test group by class
      ) t
      PIVOT (
          SUM(num)
          FOR class IN ([one],[two])
      ) p

  • 相关阅读:
    记一次内衣渗透
    mysql提权
    Token窃取与利用
    组策略首选项提权
    Windows错误配置提权
    windows内核溢出漏洞提权限
    xss漏洞
    mysql语句大全
    二叉树
    10个对所有学科都有用的Python数据可视化库
  • 原文地址:https://www.cnblogs.com/rockywood/p/6639283.html
Copyright © 2011-2022 走看看