引:

         为了举例说明,这里创建了一张成绩表,如下图所示:

        

比较:

         1、sql中,这两个函数我们仅能使用case,代码及结果如下:

   select name,
       case Subject
          when '语文' then 1
          when '数学' then 2
          when '英语' then 3   --else 3
       end  as '科目代码'
   from Results

  

   同样的,我们可以用case实现行转列,代码及结果如下:

   select Name,
            sum(case when Subject='语文' then Result end) '语文',
            sum(case when Subject='数学' then Result end) '数学',
            sum(case when Subject='英语' then Result end) '英语'
   from Results
   group by Name

  

  

         2、但是,在oracle中,这两个函数我们都可以使用,代码及结果如下:

             decode用法:select Name,decode(Subject,'语文',1,'数学',2,'英语',3) 科目代码 from results;

                               select Name,decode(Subject,'语文',1,'数学',2,3) 科目代码 from Results;

                 case用法:

  select name,
       case
          when Subject='语文' then 1
          when Subject='数学' then 2
          when Subject='英语' then 3  --else 3
       end  as 科目代码
  from Results;

  这两种方法均能达到同样的结果:

 

  同样的,我们可以使用这两个函数实现行转列,代码及结果如下:

  decode:

select
   Name,
   sum(decode(Subject,'语文',Result,0)) 语文,
   sum(decode(Subject,'数学',Result,0)) 数学,
   sum(decode(Subject,'英语',Result,0)) 英语
from Results
group by Name;

     case:

select
   Name,
   sum((case when Subject='语文' then Result else 0 end)) 语文,
   sum((case when Subject='数学' then Result else 0 end)) 数学,
   sum((case when Subject='英语' then Result else 0 end)) 英语
from Results
group by Name;

 

数据库表与行转列的中间结果(想想还是也附上)

oracle中:

select
   Name,
   decode(Subject,'语文',Result,0) 语文,
   decode(Subject,'数学',Result,0) 数学,
   decode(Subject,'英语',Result,0) 英语
from Results;

select
   Name,
   (case when Subject='语文' then Result else 0 end) 语文,
   (case when Subject='数学' then Result else 0 end) 数学,
   (case when Subject='英语' then Result else 0 end) 英语
from Results; 

结果如下:

以上内容,不对的地方请指正。此文仅想抛砖引玉...

(续)

SQL2000中动态SQL

declare @sql varchar(8000)
set @sql = 'select name '
select @sql = @sql + ' , sum(case Subject when '+ char(39) + Subject + char(39) +' then Result else 0 end) [' + Subject + ']'
from (select distinct Subject from results) as a
set @sql = @sql + ' from results group by name'
exec(@sql)

 

SQL2005中动态SQL

declare @sql varchar(8000)
select @sql = isnull(@sql + '],[' , '') + Subject from Results group by Subject
set @sql = '[' + @sql + ']'
exec ('select * from  Results pivot (max(result) for subject in (' + @sql + ')) b')

 

 

    

posted on 2010-10-13 16:24  NerverQuit  阅读(32710)  评论(3编辑  收藏  举报