select a.纳税人id,sum (isnull(b.申报的税额,0)) as 第一季度 ,
       sum (isnull(c.申报的税额,0)) as 第二季度 ,
       sum (isnull(d.申报的税额,0)) as 第三季度 ,
       sum (isnull(e.申报的税额,0)) as 第四季度 
from (select distinct 纳税人id from 你的流水表 ) a
     left outer join  你的流水表 b on a.纳税人id = b.纳税人id and datepart(qq,b申报时间) = 1
     left outer join  你的流水表 c on a.纳税人id = c.纳税人id and datepart(qq,c申报时间) = 2
     left outer join  你的流水表 d on a.纳税人id = d.纳税人id and datepart(qq,d申报时间) = 3
     left outer join  你的流水表 e on a.纳税人id = e.纳税人id and datepart(qq,e申报时间) = 4
group by a.纳税人id

解决方案 »

  1.   

    /*在 sql server下 可以这样*/
    select fid,
    sum(case datepart(qq,field_ate) when 01 then 金额 else 0 end) as 第一季度, 
    sum(case datepart(qq,field_ate) when 02 then 金额 else 0 end) as 第二季度,
    sum(case datepart(qq,field_ate) when 03 then 金额 else 0 end) as 第三季度,
    sum(case datepart(qq,field_ate) when 04 then 金额 else 0 end) as 第四季度
     from tablename group by fid
    /*在 哦oracle 下 可以这样*/
    select fid,
    sum(decode (to_char(field_ate,'mm'),'01',金额,'02',金额,'03',金额,0)) as 第一季度, 
    sum(decode (to_char(field_ate,'mm'),'04',金额,'05',金额,'06',金额,0)) as 第二季度,
    sum(decode (to_char(field_ate,'mm'),'07',金额,'08',金额,'09',金额,0)) as 第三季度,
    sum(decode (to_char(field_ate,'mm'),'10',金额,'11',金额,'12',金额,0)) as 第四季度
    from tablename group by fid
      

  2.   

    datepart(qq,'2001-09-09')
    这个函数得到的是给日期属于哪个季度整数值如select datepart(qq,'2001-09-09')得到的就是3
    表示第3季度你可以直接把这种形式放在Group by 后面,就可等到按季度分组。