表的结构如下:
personID     buyType     weight
   1          苹果        2
   2          梨          3
   3          香蕉        2
   1          梨          1
   3          苹果        3
现要查询得到如下结果:
personid   苹果   梨   香蕉
  1         2     1      0
  2         0     3      0
  3         3     0      2
请问这个查询语句怎么写?

解决方案 »

  1.   

    select personID,sum(case buyType when '苹果' then weight else 0 end) as '苹果',          sum(case buyType when '梨' then weight else 0 end) as '梨',            sum(case buyType when '香蕉' then weight else 0 end) as '香蕉' from TableName group by personID
      

  2.   

    这是针对SQL SERVER数据库的写法,你的数据库是什么,你自己改一下吧!!
      

  3.   

    上面是SQL Server 数据库
    下面的是Access
    select personID,sum(iif(personID =1 ,  weight ,0 ) as '苹果',          sum(iif(personID =2, weight , 0 ) as '梨',            sum(iif(personID =3 , weight , 0 ) as '香蕉' from TableName group by personID
      

  4.   

    declare @s varchar(4000)
    set @s=''
    select @s=@s + ',['+buyType+']=sum(case buyType when '''+buyType+''' then weight else 0 end)'
    from 表
    Group by buyType
    print @s
    exec('select personID' + @s +'from 表 Group by personID')
    go
      

  5.   

    declare @sql varchar(8000)set @sql = 'select name,' select @sql = @sql + 'sum(case subject when '''+subject+'''                           then source else 0 end) as '''+subject+''','  from (select distinct subject from test) as a select @sql = left(@sql,len(@sql)-1) + ' from test group by name'exec(@sql)go这是列数不固定的!!
      

  6.   

    VF里有这么一个分类汇总命令..呵呵,可以参考一下!(只适VF下)
    TOTAL ON <关键表达式> TO <分库库文件名> [<范围>] [FIELDS<字段名>][For <条件>][While <条件>]