---
title: "oracle行转列"
author: "jadewoo"
date: "2011-09-05T11:10:43Z"
tags: []
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2011-09-05T11:10:43Z"
id: 1165646
url: "https://jadewoo.iteye.com/blog/1165646"
---

具体Sql语句怎么写   
  比如这个例子，但是科目不固定，是动态的   
  Create   table   test   (name   char(10),km   char(10),cj   Number)   
    
  insert   into   test   values('张三','语文',80)   
  insert   into   test   values('张三','数学',86)   
  insert   into   test   values('张三','英语',75)   
  insert   into   test   values('李四','语文',78)   
  insert   into   test   values('李四','数学',85)   
  insert   into   test   values('李四','英语',78)   
    
  commit;   
  怎样实现成这样：   
  name     语文     数学     英语   
  李四     78         85         83   
  张三     80         86         75   
    
  Top
3 楼chenyiwei（无心快语）回复于 2004-11-04 11:31:56 得分 0 
<span style="color:red">select name,sum(case when km='语文' then cj else 0 end) 语文,sum(case when km='英语' then cj else 0 end) 英语,sum(case when km='数学' then cj else 0 end) 数学 from test group by name</span>一个比较笨的办法：   
  select     
  name,   
  sum(decode(km,'语文',cj,0)   语文,   
  sum(decode(km,'数学',cj,0)   数学,   
  sum(decode(km,'英语',cj,0)   英语   
  from   test   group   by   nameTop
4 楼rwpublic（rwpublic）回复于 2004-11-04 11:44:01 得分 0 
如何实现行列转换   
  1、固定列数的行列转换   
  如   
  student   subject   grade   
  ---------------------------   
  student1   语文   80   
  student1   数学   70   
  student1   英语   60   
  student2   语文   90   
  student2   数学   80   
  student2   英语   100   
  ……   
  转换为     
  语文   数学   英语   
  student1   80   70   60   
  student2   90   80   100   
  ……   
  语句如下：   
  select   student,sum(decode(subject,'语文',   grade,null))   "语文",   
  sum(decode(subject,'数学',   grade,null))   "数学",   
  sum(decode(subject,'英语',   grade,null))   "英语"   
  from   table   
  group   by   student   
    
  2、不定列行列转换   
  如   
  c1   c2   
  --------------   
  1   我   
  1   是   
  1   谁   
  2   知   
  2   道   
  3   不   
  ……   
  转换为   
  1   我是谁   
  2   知道   
  3   不   
  这一类型的转换必须借助于PL/SQL来完成，这里给一个例子   
  CREATE   OR   REPLACE   FUNCTION   get_c2(tmp_c1   NUMBER)     
  RETURN   VARCHAR2     
  IS     
  Col_c2   VARCHAR2(4000);     
  BEGIN   
  FOR   cur   IN   (SELECT   c2   FROM   t   WHERE   c1=tmp_c1)   LOOP     
  Col_c2   :=   Col_c2||cur.c2;     
  END   LOOP;     
  Col_c2   :=   rtrim(Col_c2,1);   
  RETURN   Col_c2;     
  END;   
  /   
  SQL>   select   distinct   c1   ,get_c2(c1)   cc2   from   table;即可   
    
  Top
5 楼wzs_wzs123（蓝天百云）回复于 2004-11-04 12:09:06 得分 0 
rwpublic(rwpublic)   第二种没有实现由行到列的转换Top
6 楼yjdn（文刀无尽）回复于 2004-11-04 12:17:40 得分 0 
--测试   
  declare   col1   test.km%type;                 --定义类型   
          sqlstr   varchar2(8000);   
          cursor   c_try   is   select   distinct   km   from   test;   
          begin   
          sqlstr:='';   
          open   c_try;   
          loop   
          fetch   c_try   into   col1;   
          exit   when   c_try%notfound;   
          sqlstr:=sqlstr||',sum(decode(km,'''||col1||''',cj,0))   as   '||col1;   
          exit   when   c_try%notfound;   
          end   loop;   
          close   c_try;   
          sqlstr:='create   table   tt   as   select   name'||sqlstr||'   from   test   group   by   name';   
        --tt为刚创建的一个保存结果的表   
        execute   immediate   sqlstr;   
          end;   
    
  --执行   
  select   *   from   tt;   
  结果：   
  NAME                           数学               英语               语文   
  ----------   ----------   ----------   ----------   
  李四                               85                   78                   78   
  张三                               86                   75                   80   
    
    
  --楼主给出的数据有错，李四的英语成绩应该是78Top
7 楼yjdn（文刀无尽）回复于 2004-11-04 12:18:39 得分 0 
执行完删除表tt   
  drop   table   tt;   
  /Top
8 楼wzs_wzs123（蓝天百云）回复于 2004-11-04 12:36:02 得分 0 
yjdn(无尽天空)   ，兄弟，给我一个能够直接运行的SQl语句，我对ORacle不太熟Top
9 楼yjdn（文刀无尽）回复于 2004-11-04 12:46:59 得分 50
MSSQL语句？   
  declare   @sql   varchar(8000)   
  set   @sql=''   
  select   @sql=@sql+',sum(case   km   when   '''+rtrim(km)+'''   then   cj   else   0   end)   as   '     
  from   test     
  group   by   km   
  exec('select   name'+@sql+'   from   test   group   by   name')   
    
    
  --那你的建表语句还得改一下，把number改成int



http://community.csdn.net/Expert/topic/3222/3222974.xml?temp=.5841181   
    
  col1             col2   
  -----------------   
  0001             Tom   
  0001             Jack   
  0001             Mike   
  0002             Kate   
  0002             Rose   
  0002             Fene   
    
  如何用一条SQL语句得到如下结果：   
  col1           col2   
  -----------------   
  0001           Tom,Jack,Mike   
  0002           Kate,Rose,Fene   
    
    
    
  创建自定义函数：   
  create     or     replace     function     f_ename(jobno     in     varchar2)       
  return     varchar2     is       
          
  str_return     varchar2(200);       
  cursor     c_ename(v_jobno     varchar2)     is     select     ename     from     emp     where     job=v_jobno;       
  begin       
  for     str_temp     in     c_ename(jobno)     loop       
  str_return:=str_return||str_temp.ename;       
  end     loop;       
  return     str_return;       
  end;       
  /       
    
  调用：   
  select   job,f_ename(job)   from   (select   distinct   job   from   emp);