一个动态行转列问题

qq_40608182 2017-11-29 10:54:44
表结构:
no sex
004 2
002 2
002 2
003 1
002 1

希望实现如下效果:
c1 c2
002 1 2
003 1 0
004 0 1

希望按no,sex两个字段count人数,得到二维表。
求大神帮忙解决!
...全文
109 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
碧水幽幽泉 2017-11-29
  • 打赏
  • 举报
回复
没问题的话,可以结贴了。
碧水幽幽泉 2017-11-29
  • 打赏
  • 举报
回复
已经验证,测试OK。
碧水幽幽泉 2017-11-29
  • 打赏
  • 举报
回复
问题比较简单,方法很多:

--创建测试表,添加数据
create table tt(no varchar(20 char), sex number);
insert into tt values('004',2);
insert into tt values('002',2);
insert into tt values('002',2);
insert into tt values('003',1);
insert into tt values('002',1);
commit;

--1.使用sql语句实现:
select no,
       count(case sex when 1 then 1 else null end) c1,
       count(case sex when 2 then 1 else null end) c2
  from tt
 group by no
 order by no;
 
--(2)使用存储过程动态拼接
create or replace procedure row_to_line
is
    str_sql varchar2(4000);
begin
    str_sql := ' create or replace view v_row_to_line as select no ';

    for x in (select distinct sex from tt) loop
        str_sql := str_sql || ',count(decode(sex, '||x.sex||', 1 , null)) "'||x.sex||'"';
    end loop;

    str_sql := str_sql || ' from tt group by no order by no ';

    execute immediate str_sql;

end;
/
qq_40608182 2017-11-29
  • 打赏
  • 举报
回复
no的数量不固定。

17,086

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧