偶然需要了解,学习了这篇文章,转载记录一下
自:http://blog.csdn.net/jxzkin/article/details/7949629
1.创建测试数据
[html] view plaincopy
[html] view plaincopy
希望看到查询結果:
[html] view plaincopy
[html] view plaincopy
3.使用Oracle 11g pivot方法
[html] view plaincopy
4.使用DECODE方法
[html] view plaincopy
这样的问题,要找出他的关键点来。其实就是行转列,这是一位同学在Itpub上的问题。
问题的解决:
建表:
create table t_result
(d varchar2(10),result varchar2(4));
插入数据:
insert into t_result values ('2014-01-01','胜');
insert into t_result values ('2014-01-01','胜');
insert into t_result values ('2014-01-01','负');
insert into t_result values ('2014-01-02','胜');
insert into t_result values ('2014-01-02','负');
insert into t_result values ('2014-01-02','负');
写法如下, 要扫描两次表
select t1.d,t1.c1 '胜',t2.c2 '负' from
(select count(result) c1,d from t_result where result = '胜' group by d) t1
LEFT outer join
(select count(result) c2,d from t_result where result = '负' group by d) t2
on t1.d = t2.d
行转列:
SELECT d,SUM(decode(result,'胜',1,0)),SUM(decode(result,'负',1,0))
FROM t_result
GROUP BY d
或
select d,
sum(case result when '胜' then 1 else 0 end )胜,
sum(case result when '负' then 1 else 0 end )负
from t_result group by d order by d;