select 品名,工会,SUM(CASE ISNULL(工会,0) WHEN 0 THEN 0 ELSE 工会 END) AS 数量
into #temptable from 表
group by 品名,工会DELETE #temptable where 数量 = 0select * from  #temptable 

解决方案 »

  1.   

    select 品名,'工会' AS 部门,
           SUM(CASE ISNULL(工会,0) WHEN 0 THEN 0 ELSE 工会 END) AS 数量
    into #temptable from 表
    group by 品名,工会INSERT #temptable
    select 品名,'学生处',
           SUM(CASE ISNULL(学生处,0) WHEN 0 THEN 0 ELSE 学生处 END) AS 数量
    into #temptable from 表
    group by 品名,学生处INSERT #temptable
    select 品名,'计机系',
           SUM(CASE ISNULL(计机系,0) WHEN 0 THEN 0 ELSE 计机系 END) AS 数量
    into #temptable from 表
    group by 品名,计机系select 品名,'数学系',
           SUM(CASE ISNULL(数学系,0) WHEN 0 THEN 0 ELSE 数学系 END) AS 数量
    into #temptable from 表
    group by 品名,数学系DELETE #temptable where 数量 = 0select * from  #temptable
      

  2.   

    v_import
    (bmdm,bm,pmdm,pm,rq,cp,gg,dw,sl)
      

  3.   

    列1     列2      列3
    A4      工会     4
    A4      学生处   2
    A3      学生处   1
    A3      计机系   1declare @sql varchar(8000)
    set @sql = 'select 列1'
    select @sql = @sql + ',sum(case 列2 when '''+列2+''' then 列3 else 0 end) ['+列2+']'
      from (select distinct 列2 from 有一表) as a
    select @sql = @sql+' from 你的表 group by 列1'exec(@sql)
    go
      

  4.   

    bmdm     bm        pmdm    pm        sl            ..............
    2001 院办 2001 扫把 9.0
    2001 院办 1002 A3纸 9.0
    2001 院办 1001 A4纸 3.0
    2001 院办 1002 A3纸 3.0
    2001 院办 1002 A3纸 3.0
    2001 院办 1002 A3纸 9.0
    2003 工会 2001 扫把 5.0
    2003 工会 1003 A1纸 23.0
    2003 工会 1003 A1纸 23.0
    2004 后财处 1005 档案袋 234.0
    2004 后财处 1002 A3纸 50.0
    2004 后财处 1002 A3纸 50.0
    2005 教务处 2001 扫把 9.0
    2005 教务处 2001 扫把 9.0
    2005 教务处 1002 A3纸 6.0
    2006 学生处 1007 16K复印纸 5.0
    2006 学生处 1007 16K复印纸 44.0t_import(bmdm,bm,pmdm,pm,rq,cp,dw,gg,dj,sl)
    (部门代码,部门,品名代码,品名,日期,厂牌,单位,规格,单价,数量)
    现在只有这张表我怎么实现以上的组合统计.是不是还要建多一张表呢?哥们
      

  5.   

    pengdali(大力 V3.0) 
    按您的方法解决了问题,还有合计一项又如何做呢?我如何把这些代码变成一张视图,
    因为我要出报表,生成一张视图才行呀
      

  6.   

    create procedure p_export@rq varchar(10)asdeclare @sql varchar(8000)set @sql = 'select pm'select @sql = @sql + ',sum(case bmdm when '''+bmdm+''' then sl else 0 end) ['+bmdm+']'from (select distinct code bmdm from t_dictionary where type='BM' and code like '2%') as aselect @sql = @sql+',sum(sl) heji into ##t_temp from t_export where datepart(mm,rq)='''+@rq+''' group by pm 'exec(@sql)go select * from ##t_tempgodrop table ##t_temp
      

  7.   

    select pm,bm,sum(sl) from t_importgroup by pm,bm