矩阵转化

一道SQL语句面试题,关于group by
表内容:
2005-05-09 胜
2005-05-09 胜
2005-05-09 负
2005-05-09 负
2005-05-10 胜
2005-05-10 负
2005-05-10 负

如果要生成下列结果, 该如何写sql语句?

            胜 负
2005-05-09 2 2
2005-05-10 1 2

 

 

解答:

create table  tmp(rq varchar(10),shengfu nchar(1));
insert into  tmp values('2005-05-09','胜');
insert into  tmp values('2005-05-09','胜');
insert into  tmp values('2005-05-09','负');
insert into  tmp values('2005-05-09','负');
insert into  tmp values('2005-05-10','胜');
insert into  tmp values('2005-05-10','负');
insert into  tmp values('2005-05-10','负');

 commit;

 

 

 select rq 时间, max(sheng) 胜, max(fu)负
from (
    select rq, decode(shengfu,'胜', all_num,'') sheng,
     decode(shengfu,'负',all_num,'') fu
     from (
          select rq,shengfu,count(shengfu) all_num
               from tmp group by rq, shengfu
)
      ) group by rq order by rq

 

  或者可以这样:

 

select rq,sum(to_number(case when shengfu='胜' then replace(shengfu,'胜','1') else '0' end)) 胜,
sum(to_number(case when shengfu='负' then replace(shengfu,'负','1') else '0' end)) 负
from tmp group by rq


 注意replace的用法

换一下: 如果数据库中胜变为1, 负为0

update tmp set shengfu=(  case  when shengfu='胜' then 1  when shengfu='负' then 0 end);

commit;

 

select rq,count(case when shengfu=1 then 1 end ) 胜,
count(case when shengfu=0  then 0 end ) 负
from tmp group by rq

 

更为简单的方法:

select rq, sum(decode(shengfu,'胜',1 )) 胜, sum(decode(shengfu,'负',1)) 负 from tmp group by rq order by rq;

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值