有一表结构如下
id   index xm    xm1    xm2     hz
8     3    wdy    5.0    5.0    10.00
9     3    hzs    5.0    5.0    12.00
10    3    xjb    4.0    6.0    15.00
16    4    wdy    5.0    5.0    11.00
17    4    hzs    5.0    5.0    114.00
18    4    xjb    5.0    5.0    20.00
19    5    wdy    4.0    6.0    12.00
20    5    hzs    5.0    5.0    18.00
21    5    xjb    4.0    6.0    19.00
=====================================================================
现在要实现如下查询结果
index     wdy       hzs      xjb
 3       10.00     12.00    15.00
 4       11.00     114.00   20.00
 5       12.00     18.00    19.00
===========================================================================
高手们 如何实现!!!

解决方案 »

  1.   

    select 
       [index],
        wdy=sum(case when xm='wdy' then hz else 0 end),
        hzs=sum(case when xm='hzs' then hz else 0 end),
        xjb=sum(case when xm='xjb' then hz else 0 end)
    from tb group by [index]
      

  2.   

    ----------------------------------------------------------------
    -- Author :fredrickhu(小F 向高手学习)
    -- Date   :2009-08-12 14:48:03
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([id] int,[index] int,[xm] varchar(3),[xm1] numeric(2,1),[xm2] numeric(2,1),[hz] numeric(5,2))
    insert [tb]
    select 8,3,'wdy',5.0,5.0,10.00 union all
    select 9,3,'hzs',5.0,5.0,12.00 union all
    select 10,3,'xjb',4.0,6.0,15.00 union all
    select 16,4,'wdy',5.0,5.0,11.00 union all
    select 17,4,'hzs',5.0,5.0,114.00 union all
    select 18,4,'xjb',5.0,5.0,20.00 union all
    select 19,5,'wdy',4.0,6.0,12.00 union all
    select 20,5,'hzs',5.0,5.0,18.00 union all
    select 21,5,'xjb',4.0,6.0,19.00
    --------------开始查询--------------------------
    declare @sql varchar(8000)
    set @sql = 'select  [index]'
    select @sql = @sql + ' , sum(case xm when ''' + xm + ''' then hz else 0 end) [' + xm + ']'
    from (select distinct xm from tb) as a
    set @sql = @sql + ' from tb group by [index]'
    exec(@sql) 
    ----------------结果----------------------------
    /*index       hzs                                      wdy                                      xjb                                      
    ----------- ---------------------------------------- ---------------------------------------- ---------------------------------------- 
    3           12.00                                    10.00                                    15.00
    4           114.00                                   11.00                                    20.00
    5           18.00                                    12.00                                    19.00*/
      

  3.   


    2楼正解但是index一定要[]因为是关键字 不然会报错的
    select * from table_1select [index],wdy=max(case when xm='wdy' then hz else 0 end), 
      hzs=max(case when xm='hzs' then hz else 0 end), 
      xjb=max(case when xm='xjb' then hz else 0 end) 
    from table_1 group by [index] id          index       xm                                                 xm1         xm2         hz
    ----------- ----------- -------------------------------------------------- ----------- ----------- -----------
    1           3           wdy                                                5           5           10
    2           3           hzs                                                5           5           12
    3           3           xjb                                                4           6           15
    4           4           wdy                                                5           5           11
    5           4           hzs                                                5           5           114
    6           4           xjb                                                5           5           20
    7           5           wdy                                                4           6           12
    8           5           hzs                                                5           5           18
    9           5           xjb                                                4           6           19(9 行受影响)index       wdy         hzs         xjb
    ----------- ----------- ----------- -----------
    3           10          12          15
    4           11          114         20
    5           12          18          19
      

  4.   

    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([id] int,[index] int,[xm] varchar(3),[xm1] numeric(2,1),[xm2] numeric(2,1),[hz] numeric(5,2))
    insert [tb]
    select 8,3,'wdy',5.0,5.0,10.00 union all
    select 9,3,'hzs',5.0,5.0,12.00 union all
    select 10,3,'xjb',4.0,6.0,15.00 union all
    select 16,4,'wdy',5.0,5.0,11.00 union all
    select 17,4,'hzs',5.0,5.0,114.00 union all
    select 18,4,'xjb',5.0,5.0,20.00 union all
    select 19,5,'wdy',4.0,6.0,12.00 union all
    select 20,5,'hzs',5.0,5.0,18.00 union all
    select 21,5,'xjb',4.0,6.0,19.00
    select * from (select [index], xm ,hz from tb) m
    pivot
    (
     sum(hz) for xm in(wdy,hzs,xjb)
    ) p/*
    index       wdy                                     hzs                                     xjb
    ----------- --------------------------------------- --------------------------------------- ---------------------------------------
    3           10.00                                   12.00                                   15.00
    4           11.00                                   114.00                                  20.00
    5           12.00                                   18.00                                   19.00(3 行受影响)
    */
      

  5.   


    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([id] int,[index] int,[xm] varchar(3),[xm1] numeric(2,1),[xm2] numeric(2,1),[hz] numeric(5,2))
    insert [tb]
    select 8,3,'wdy',5.0,5.0,10.00 union all
    select 9,3,'hzs',5.0,5.0,12.00 union all
    select 10,3,'xjb',4.0,6.0,15.00 union all
    select 16,4,'wdy',5.0,5.0,11.00 union all
    select 17,4,'hzs',5.0,5.0,114.00 union all
    select 18,4,'xjb',5.0,5.0,20.00 union all
    select 19,5,'wdy',4.0,6.0,12.00 union all
    select 20,5,'hzs',5.0,5.0,18.00 union all
    select 21,5,'xjb',4.0,6.0,19.00
    select 
       [index],
        wdy=sum(case when xm='wdy' then hz else 0 end),
        hzs=sum(case when xm='hzs' then hz else 0 end),
        xjb=sum(case when xm='xjb' then hz else 0 end)
    from tb group by [index]
    --------------------------------------------------------
    index    wdy    hzs    xjb                                      
    3 10.00 12.00 15.00
    4 11.00 114.00 20.00
    5 12.00 18.00 19.00
    (所影响的行数为 3 行)
      

  6.   

    又见行转列,xiaoF 张三呢
      

  7.   

    SELECT 
       [INDEX],
        WDY=SUM(CASE WHERE XM='WDY' THEN HZ ELSE 0 END ),
        HZS=SUM(CASE WHERE XM='HZS' THEN HZ ELSE 0 END ),
        XJB=SUM(CASE WHERE XM='XJB' THEN HZ ELSE 0 END )       
    FROM TB GROUP BY [INDEX]
    好像昨天 发过
      

  8.   

    --行列互转
    /******************************************************************************************************************************************************
    以学生成绩为例子,比较形象易懂整理人:中国风(Roy)日期:2008.06.06
    ******************************************************************************************************************************************************/--1、行互列
    --> --> (Roy)生成測試數據
     
    if not object_id('Class') is null
    drop table Class
    Go
    Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
    Insert Class
    select N'张三',N'语文',78 union all
    select N'张三',N'数学',87 union all
    select N'张三',N'英语',82 union all
    select N'张三',N'物理',90 union all
    select N'李四',N'语文',65 union all
    select N'李四',N'数学',77 union all
    select N'李四',N'英语',65 union all
    select N'李四',N'物理',85 
    Go
    --2000方法:
    动态:declare @s nvarchar(4000)
    set @s=''
    Select  @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
    from Class group by[Course]
    exec('select [Student]'+@s+' from Class group by [Student]')
    生成静态:select 
    [Student],
    [数学]=max(case when [Course]='数学' then [Score] else 0 end),
    [物理]=max(case when [Course]='物理' then [Score] else 0 end),
    [英语]=max(case when [Course]='英语' then [Score] else 0 end),
    [语文]=max(case when [Course]='语文' then [Score] else 0 end) 
    from 
    Class 
    group by [Student]GO
    动态:declare @s nvarchar(4000)
    Select  @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course]
    exec('select * from Class pivot (max([Score]) for [Course] in('+@s+'))b')生成静态:
    select * 
    from 
    Class 
    pivot 
    (max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b生成格式:
    /*
    Student 数学          物理          英语          语文
    ------- ----------- ----------- ----------- -----------
    李四      77          85          65          65
    张三      87          90          82          78(2 行受影响)
    */------------------------------------------------------------------------------------------
    go
    --加上总成绩(学科平均分)--2000方法:
    动态:declare @s nvarchar(4000)
    set @s=''
    Select  @s=@s+','+quotename([Course])+'=max(case when [Course]='+quotename([Course],'''')+' then [Score] else 0 end)'
    from Class group by[Course]
    exec('select [Student]'+@s+',[总成绩]=sum([Score])  from Class group by [Student]')--加多一列(学科平均分用avg([Score]))生成动态:select 
    [Student],
    [数学]=max(case when [Course]='数学' then [Score] else 0 end),
    [物理]=max(case when [Course]='物理' then [Score] else 0 end),
    [英语]=max(case when [Course]='英语' then [Score] else 0 end),
    [语文]=max(case when [Course]='语文' then [Score] else 0 end),
    [总成绩]=sum([Score]) --加多一列(学科平均分用avg([Score]))
    from 
    Class 
    group by [Student]go--2005方法:动态:declare @s nvarchar(4000)
    Select  @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号
    exec('select [Student],'+@s+',[总成绩] from (select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a 
    pivot (max([Score]) for [Course] in('+@s+'))b ')生成静态:select 
    [Student],[数学],[物理],[英语],[语文],[总成绩] 
    from 
    (select *,[总成绩]=sum([Score])over(partition by [Student]) from Class) a --平均分时用avg([Score])
    pivot 
    (max([Score]) for [Course] in([数学],[物理],[英语],[语文]))b 生成格式:/*
    Student 数学          物理          英语          语文          总成绩
    ------- ----------- ----------- ----------- ----------- -----------
    李四      77          85          65          65          292
    张三      87          90          82          78          337(2 行受影响)
    */go--2、列转行
    --> --> (Roy)生成測試數據
     
    if not object_id('Class') is null
    drop table Class
    Go
    Create table Class([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int)
    Insert Class
    select N'李四',77,85,65,65 union all
    select N'张三',87,90,82,78
    Go--2000:动态:declare @s nvarchar(4000)
    select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''')--isnull(@s+' union all ','') 去掉字符串@s中第一个union all
    +',[Score]='+quotename(Name)+' from Class'
    from syscolumns where ID=object_id('Class') and Name not in('Student')--排除不转换的列
    order by Colid
    exec('select * from ('+@s+')t order by [Student],[Course]')--增加一个排序生成静态:
    select * 
    from (select [Student],[Course]='数学',[Score]=[数学] from Class union all 
    select [Student],[Course]='物理',[Score]=[物理] from Class union all 
    select [Student],[Course]='英语',[Score]=[英语] from Class union all 
    select [Student],[Course]='语文',[Score]=[语文] from Class)t 
    order by [Student],[Course]go
    --2005:动态:declare @s nvarchar(4000)
    select @s=isnull(@s+',','')+quotename(Name)
    from syscolumns where ID=object_id('Class') and Name not in('Student') 
    order by Colid
    exec('select Student,[Course],[Score] from Class unpivot ([Score] for [Course] in('+@s+'))b')go
    select 
    Student,[Course],[Score] 
    from 
    Class 
    unpivot 
    ([Score] for [Course] in([数学],[物理],[英语],[语文]))b生成格式:
    /*
    Student Course Score
    ------- ------- -----------
    李四      数学      77
    李四      物理      85
    李四      英语      65
    李四      语文      65
    张三      数学      87
    张三      物理      90
    张三      英语      82
    张三      语文      78(8 行受影响)
    */
      

  9.   

    如果项目列数据多的话,用如下代码,否则,用楼上哥哥们说的!SQL code/*★★★★★soft_wsx  2009-08-09 14:08:28.733★★★★★*/
    --原始数据如下
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([id] int,[index] int,[xm] varchar(3),[xm1] numeric(2,1),[xm2] numeric(2,1),[hz] numeric(5,2))
    insert [tb]
    select 8,3,'wdy',5.0,5.0,10.00 union all
    select 9,3,'hzs',5.0,5.0,12.00 union all
    select 10,3,'xjb',4.0,6.0,15.00 union all
    select 16,4,'wdy',5.0,5.0,11.00 union all
    select 17,4,'hzs',5.0,5.0,114.00 union all
    select 18,4,'xjb',5.0,5.0,20.00 union all
    select 19,5,'wdy',4.0,6.0,12.00 union all
    select 20,5,'hzs',5.0,5.0,18.00 union all
    select 21,5,'xjb',4.0,6.0,19.00
    --------------开始查询--------------------------
    declare @sql varchar(8000)
    set @sql = 
    select @sql = @sql + ' , sum(case xm when ''' + xm + ''' then hz else 0 end) [' + xm + ']'set @sql = @sql + 
    exec(@sql) 
    alter proc dbo.hljcbb  -- exec dbo.hljcbb
    as
    declare @sql_head                           nvarchar(4000),
            @sql_foot                           nvarchar(4000),
            @sql_body                           nvarchar(4000),
            @sql_variable_definition            nvarchar(4000),
            @sql_variable_init                  nvarchar(4000),
            @sql_variable_set                   nvarchar(4000),
            @groups                             varchar(100)-->>>>>>1、确定需要定义的变量个数>>>>>>>>>drop table #1
    select
       id=identity(int,0,1),
       gs=0,
       fieldvalue=CAST(
                       N','+quotename(xm)
                       +N'=max(case when xm='+quotename(xm,N'''')
                       +N' then hz else 0 end)'
                       as Nvarchar(4000))
      into #1 from (select distinct xm from tb) as a                                  --要修改的临时表生成部分
      group by [xm]
      
      --select * from #1
      
     -->>>>>2、分临时时表,通过G字段的值决定当前的处理代码应保存在那个变量中
     update A 
       set @groups=id/l,gs=@groups
       from #1 a 
         cross join(select l=3800/max(LEN(FIELDVALUE)) from #1)b-->>>>>>3.生成数据处理语句--select * from #1
    select @sql_head=N''''+REPLACE('select  [index]',N'''',N'''''')+N'''',            --要修改的部分
           @sql_foot=N''''+REPLACE(' from tb group by [index]',N'''',N'''''')+N'''',  --要修改的部分
           @sql_variable_definition=N'',
           @sql_variable_init=N'',
           @sql_variable_set=N'',
           @sql_body=N''
    while @groups>=0
      select 
        @sql_variable_definition=N',@'+@groups+N' nvarchar(4000)'+@sql_variable_definition,
        @sql_variable_init=N',@'+@groups+N'=N''''',
        @sql_variable_set=N',@'+@groups+N'=case 
                                             when gs='+@groups+N' then @'+@groups+N'+fieldvalue
                                             else @'+@groups+N'
                                           end'+@sql_variable_set,
        @sql_body=N'+@'+@groups+@sql_body,
        @groups=@groups-1--去掉各变量中多余的前导符号
    select 
        @sql_variable_definition=STUFF(@sql_variable_definition,1,1,N''), --stuff删除指定位置开始,指定数目的字符串,并在指定位置插入字符
        @sql_variable_init=STUFF(@sql_variable_init,1,1,N''),
        @sql_variable_set=STUFF(@sql_variable_set,1,1,N''),
        @sql_body=STUFF(@sql_body,1,1,N'')
    print @sql_head
    print @sql_foot
    print @sql_variable_definition
    print @sql_variable_set
    print @sql_variable_init
    print @sql_body
    --执行
    exec(N'declare '+@sql_variable_definition+
         N'select '+@sql_variable_init+
         N'select '+@sql_variable_set+
         N' from #1
    exec(N'+@sql_head+N'
            +'+@sql_body+N'
            +'+@sql_foot+N')')
    goexec dbo.hljcbb  --执行存储过程
    /*
    结果
    index    hzs    wdy    xjb
    3    12.00    10.00    15.00
    4    114.00    11.00    20.00
    5    18.00    12.00    19.00
    */
      

  10.   

    select * from (select [index], xm ,hz from tb) dd
    pivot( sum(hz) for xm in(wdy,hzs,xjb)) cc

    一句搞定!