年度 月份 代码 资金A 资金B
2009 1    301   1000  200 
2010 3    501   500   400一个表类似于这样的结构,其中年度是从2000-2010年 月分1-12 代码有很多其中包括301,501,502,503等,在这里我只想查询其中符合条件的年度和月分,
条件是 相同年度,相同月分的
(代码为301的资金A-资金B)/(代码为501的资金A+代码为502的资金B+代码为503的资金A)<1请大家给咱一点指导,多多感谢

解决方案 »

  1.   

    select year,month,sum(case 代码 when 301 then 资金A-资金B else 0 end)/sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else0)
      from table
    group by year,month
    having sum(case 代码 when 301 then 资金A-资金B else 0 end)/sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else0)<1
    大概是这样, 你可以试试.
      

  2.   

    上面case少写了个end
    select year,month,sum(case 代码 when 301 then 资金A-资金B else 0 end)/sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else 0 end)
      from table
    group by year,month
    having sum(case 代码 when 301 then 资金A-资金B else 0 end)/sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else 0 end)<1
      

  3.   


    [code=SQL]
    select 年度,月份 from (
    select 年度,月份,
    sum(case when 代码=301 then 资金A else 0 end) as 301A,
    sum(case when 代码=301 then 资金B else 0 end) as 301B,
    sum(case when 代码=501 then 资金A else 0 end) as 501A,
    sum(case when 代码=502 then 资金B else 0 end) as 502B
    sum(case when 代码=503 then 资金A else 0 end) as 503A
    from 表
    group by 年度,月份
    ) a where (301A-301B)/(501A+502B+503A)<1[/code]
      

  4.   

    select a.*
    from
    (select 年度,月份,代码,
    sum(case when 代码='301' then 资金A-资金B else 0 end) sum_301,
    sum(case when 代码='501' then 资金A else 0 end) sum_501,
    sum(case when 代码='502' then 资金B else 0 end) sum_502,
    sum(case when 代码='503' then 资金A else 0 end) sum_503
    from tb
    group by 年度,月份,代码) a
    where sum_301/(sum_501+sum_502+sum_503)<1
      

  5.   

    如果只是要年月的话select year,month
      from table
     group by year,month
    having sum(case 代码 when 301 then 资金A-资金B else 0 end)/sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else0)<1
      

  6.   

    晕,你就不能变通一下啊.
    select year,month
      from table
     group by year,month
    having sum(case 代码 when 301 then 资金A-资金B else 0 end)<sum(case 代码 when 501 then 资金A when 502 then 资金A when 503 then 资金A else0)