zoukankan      html  css  js  c++  java
  • sqlserver2000 下,行列转换(从简单到复杂二)

    接上篇,要是课程我不知道怎么办呢?“办法比困难多”,考虑后得出一个解决方法。

    就是用字符串拼接的方法,把所有的课程都拼接起来。不是很繁琐。代码如下:


    USE TEMPDB

    IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'TEMPDB.[dbo].[#temptable]'AND type in (N'U'))
    begin
        
    drop table #temptable
    end
    create table #temptable
    (
     ID 
    int ,
     course 
    varchar(10),
     Point 
    int
    )

    insert into #temptable
    select 1 ,'语文',87
    union all
    select 1 ,'数学',98
    union all
    select 2,'语文',54
    union all
    select 2,'化学',97
    union all
    select 2,'数学',92
    union all
    select 4,'数学',86
    union all
    select 5 ,'数学',65
    union all
    select 6,'语文',76
    union all
    select 6,'数学',76
    union all
    select 6,'化学',76

    select * from #temptable

    declare @str varchar(2000)
    set @str = ' select ID '
    select @str = @str + '  ,  max(case when course = ''' + course +''' then Point else 0 end )  as   ''' + course + '''' 
    from  (select distinct course from #temptable) A  
    set @str  = @str + ' from #temptable group by ID '
    print @str

    exec (@str)

    解决啦,说真的这个不是很复杂的问题, 刚要高兴,有哥们说这种问题在sql2005中很见到就能解决。

    简单调查下,发现两个关键字PIVOT/UNPIVOT,可以轻松实现行列转换的需求。 

    看来得继续前进啦,看看sql2005如何简单实现的。(未完待续)

  • 相关阅读:
    对白
    泰芒了
    下雨
    聚会
    周末了
    One English Sentence
    Struts拦截器使用
    JAVA语法题
    jquery全选框的实现
    实战3--设计实体, 映射实体
  • 原文地址:https://www.cnblogs.com/redfox241/p/1440888.html
Copyright © 2011-2022 走看看