select
    a.消费日期,
    a.消费地点,
    a.消费类别,
    a.消费金额,
    (select sum(消费金额) from 表 where datediff(mm,消费日期,a.消费日期)=0) as 截至今天本月消费金额,
    (select sum(消费金额) from 表 where datediff(yy,消费日期,a.消费日期)=0)as 截至今天本年消费金额
from
    表 a

解决方案 »

  1.   

    select 消费日期,消费地点, 消费类别, 消费金额,
           (select sum(消费金额) from t t_m 
                where t_m.消费地点=t.消费地点 and t_m.消费类别=t.消费类别
                  and t_m.消费日期<=t.消费日期
                  and datediff(month, t_m.消费日期, t.消费日期)=0) 消费金额_m,
           (select sum(消费金额) from t t_y 
                where t_y.消费地点=t.消费地点 and t_y.消费类别=t.消费类别
                  and t_y.消费日期<=t.消费日期
                  and datediff(month, t_y.消费日期, t.消费日期)=0) 消费金额_y
        from t
      

  2.   

    select
        a.消费日期,
        a.消费地点,
        a.消费类别,
        a.消费金额,
        (select sum(消费金额) from 表 where datediff(mm,消费日期,@rq)=0) as 截至今天本月消费金额,
        (select sum(消费金额) from 表 where datediff(yy,消费日期,@rq)=0)as 截至今天本年消费金额
    from
        表 a
      

  3.   

    select 消费日期,消费地点,消费类别,消费金额,
    sum(cast when month(消费日期)=month(getdate()) then 消费金额 else 0) as 截至今天本月消费金额,
    sum(cast when year(消费日期)=year(getdate()) then 消费金额 else 0) as 截至今天本年消费金额
    from 表