sheet的   表字段:sheet_id,made_date
 produce_bear 表 的字段:sheet_id,bear_q
sheet_id 的字段是‘年’-’月‘-‘日’
想按照月份小计,最后一年合计
我写得sql是:select case when grouping(left(right(p.sheet_id,7),2))=1 then '合计' else left(right(p.sheet_id,7),2) end 月份,case when grouping (p.sheet_id)=1 and grouping (left(right(p.sheet_id,7),2))=0 then '小计' else p.sheet_id end 单号,max(p.meterial_id),max(t.made_date) ,sum(bear_q) as 啤数 from produce_bear p inner join sheet t on t.sheet_id=p.sheet_id where p.meterial_id='02100330000109' group by left(right(p.sheet_id,7),2),p.sheet_id with rollup 
结果显示为:
月份   sheet_id              meterial_id                made_date                                 bear_q
2         2011-02-0001    021001                   2011-02-05                               100
2         2011-02-0002    021001                   2011-02-06                               100
2         2011-02-0003    021001                   2011-02-07                                100
2         小计                   021001                   2011-02-07                             300
3        2011-03-0001    021001                   2011-03-05                               23     3        2011-03-0002    021001                   2011-03-07                                100
3         小计                   021001                   2011-03-07                               123
合计    null                      021001                   2011-03-07                             423想在小计和合计那里就显示,meterial_id    和bear_q,不显示sheet_id,made_date

解决方案 »

  1.   


    YEAR(sheet_id),month(sheet_id) 分组
      

  2.   

    这个不是已经是按照月份分组的,按年的不急!
    按月份的分组,但是其他的列显示,不知道怎么显示,meterial_id,made_date纯属显示就可以的,不想分组,或者用max(),min()函数,这会造成在小计和合计的记录里显示的内容多了
      

  3.   

    你需要使用三段SQL,然后union all起来.
    按照每日的一个SQL
    union all
    按照每月的一个sql. --这里在相应字段写上小计.
    union all
    按照每年的一个sql. --这里在相应字段写上合计.