有表test,结果如下:
type     state      value
1          01         100
2          01         200
3          01         300
1          02         400
2          02         500
3          02         600
1          03         700
2          03         800
3          03         900需要求出以下结果:
以state分组,type为列头,state     type1     type2    type3
 
01         100      200       300
02         400      500       600
03         700      800       900请问sql语句怎么写?  

解决方案 »

  1.   

    select state,sum(decode(type,'1',value,0)) type1,sum(decode(type,'2',value,0)) type2,sum(decode(type,'3',value,0)) type3
    from table
    gropu by state
      

  2.   

    如果固定TYPE就三种,并且每个STATE里三个TYPE都是唯一一条的话可以这样写select state,sum(decode(type,1,value,0)) type1,sum(decode(type,2,value,0)) type2,sum(decode(type,3,value,0)) type3
    from test
    group by state
      

  3.   

    如果TYPE类型不是固定数,而且每个STATE的每个TYPE不是唯一一条,那就要根据显示要求来写了,语句不同了
    呵呵,我写的和一楼的除了在TYPE类型上有所不同外,其它一样,如果TYPE是VARCHAR就用'1',如果是NUMBER,就直接用1就行了
    其实都可以用的,只不过如果是VARCHAR类型的话,加上''严谨点
      

  4.   

    type不是固定的。上面的写法是不对的吧。
      

  5.   

    type不是固定的,那最好是用存储过程
    这种问题比较讨厌,也老有人问,典型的行列转换加不固定的行列
      

  6.   

    对,如果行转列固定的话就用上面写的方法sum(decode(type,1,value,0)) 。如果不是固定的话只能通过动态语句来做,不过实现起来比较麻烦。
      

  7.   

    create table test1 (type int,state varchar(10),value int)
    insert into test1 select 1,'01',100
    union all select 2,'01',200
    union all select 3,'01',300
    union all select 1,'02',400
    union all select 2,'02',500
    union all select 3,'02',600
    union all select 1,'03',700
    union all select 2,'03',800
    union all select 3,'03',900declare @sql varchar(1000)
    set @sql='select state'
    select @sql=@sql+',[type'+cast(type as varchar)+']=max(case type when '''+ cast(type as varchar) +''' then value else 0 end)' 
    from (select distinct type from test1)a
    set @sql=@sql+' from test1 group by state'
    exec(@sql)
      

  8.   

    create   table   test1   (type   int,state   varchar(10),value   int) 
    insert   into   test1   select   1,'01',100 
    union   all   select   2,'01',200 
    union   all   select   3,'01',300 
    union   all   select   1,'02',400 
    union   all   select   2,'02',500 
    union   all   select   3,'02',600 
    union   all   select   1,'03',700 
    union   all   select   2,'03',800 
    union   all   select   3,'03',900 declare   @sql   varchar(1000) 
    set   @sql='select   state' 
    select   @sql=@sql+',[type'+cast(type   as   varchar)+']=max(case   type   when   '''+   cast(type   as   varchar)   +'''   then   value   else   0   end)'   
    from   (select   distinct   type   from   test1)a 
    set   @sql=@sql+'   from   test1   group   by   state' 
    exec(@sql)