求教: 有张表: 部门 月份 人工费
1 7 10
2 7 20
3 8 30
4 8 40现在要求的查询结果是:输入本月月份,同时出来上月月份的数据: 部门 本月人工费 上月人工费
1
2
3
4

解决方案 »

  1.   

    如果是统计select sum(decode(月份, '&&month', 1, 0)) "本月总人工费", sum(decode(月份, '&&month'+1, 1, 0)) "上月总人工费" from t1 where 月份=&&month or 月份=(&&month-1)如果是显示的话select a.部门 "部门", a.人工费 "本月人工费", b.人工费 "上月人工费" from t1 left join t1 b on a.部门=b.部门 and b.月份=a.月份-1;不过这个是简单的case,遇到1月的就出问题。你们这里是不是只是保留一个年度的信息呀。
      

  2.   


    不好意思掉叻替换变量select a.部门 "部门", a.人工费 "本月人工费", b.人工费 "上月人工费" from t1 left join t1 b on a.部门=b.部门 and b.月份=a.月份-1 where a.月份=&month; 
      

  3.   

    我的一般做法,用两层SQL
    第一层里月份多取一个月,然后用LAG函数
    第二层SQL在日期上做过滤,把多取的一个月过滤掉
      

  4.   

    你的月份应该带年份的吧,比如:200907.
    我试过了,可以这样写:比如你的表叫tablea,部门dept  月份叫MON,费用money,
    select 
    dept,sum(money),(select sum(money) from tablea b
    where b.mon=a.mon-1
    and   a.dept=dept)
     from tablea a
    where  a.mon=200907  --你输入月份,
    group by dept,mon