一个sql的行列转置的例子。

有这样一个AAA表如下所示:

name    score    color

jim         10        red
jim         20       blue
jim         20       green
jim         1         black
glin        2          red
glin        33        blue
glin        21       green
glin        19       black
bob        22       red
bob        39       blue
bob        11      green
bob        11      black

要转置成如下所示的BBB表

name red  blue green  black
jim     10    20     20        1
bob    22    39    11       11
glin     2      33    21       19

 

使用的sql如下:

select R.name ,R.s red,B.s blue,G.s green ,Bk.s black
from( select name,sum(score)s from AAA where color='red' group by name ) R,
    ( select name,sum(score)s from AAA where color='blue' group by name ) B,
    ( select name,sum(score)s from AAA where color='green' group by name ) G,
    ( select name,sum(score)s from AAA where color='black' group by name ) Bk
where R.name = B.name and B.name = G.name and G.name = Bk.name

相当于group by之后把每个人的某一种颜色的分数统计成一个数据集,再把这几个响应的数据集做表连接拼起来。

 

如果反过来,指导BBB表,要返回成AAA表,sql的写法是怎样呢?

select name, red score,'red' color from BBB
union 
select name, blue score,'blue' color from BBB
union 
select name, green score,'green' color from BBB
union 
select name, black score,'black' color from BBB

就是把几个查询集并起来。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值