• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wood132
博客园    首页    新随笔    联系   管理    订阅  订阅

行转列

给定一个数据库的表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

 

posted @ 2017-03-29 13:14  wood132  阅读(142)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3