ID   月份   数量
1   2      2
2   2      3
3   3      5
4   4      1
5   4      2需要的结果本月月份 本月数量累计 本月前总累计数量
4        3            10
这样的查询,我是使用两条SQL语句拼出的来,一条查询本月的数量,一条查询本月前的所有数量
有没有更有效的写法呢?谢谢大家了

解决方案 »

  1.   

    select 本月月份=month(getdate()),
           本月数量累计=sum( case when 月份=month(getdate()) then 数量 else 0 end),
           本月前总累计数量=sum( case when 月份<=month(getdate()) then 数量 else 0 end)
    from tb
      

  2.   


      select DATEPART(month,getdate()) as 本月月份
      ,(select SUM(数量) from tb where 月份 =  DATEPART(month,getdate())) as 本月数量
      ,( select SUM(数量) from tb where 月份 < DATEPART(month,getdate())) as 本月之前数量
      from tb
      

  3.   

    select
      month(getdate()) as 本月月份,
      数量 as 本月数量累计,
      (select sum(数量) as 数量 from tb)-isnull(数量,0) as 本月前总累计数量
    from
      (select 月份,sum(数量) as 数量 from tb where 月份=month(getdate()) group by 月份)t 
      

  4.   

    select
     month(getdate()) as 本月月份,
     sum( case when 月份=month(getdate()) then 数量 else 0 end) as 本月数量累计,
     sum( case when 月份<=month(getdate()) then 数量 else 0 end) as 本月前总累计数量
    from
     tb
      

  5.   

    select 本月月份=月份,本月数量累计=sum(数量),
    本月前总累计数量=(select sum(数量) from tb where 月份<4) 
    from tb where 月份=4
      

  6.   


    use tempdb;
    /*
    create table t2
    (
    ID int not null,
    月份 int not null,
    数量 int not null
    );
    insert into t2(ID,月份,数量)
    values
    (1,2,2),
    (2,2,3),
    (3,3,5),
    (4,4,1),
    (5,4,2);
    */
    select 
    t2.月份 as [本月月份],
    SUM(t2.数量) as [本月数量累计],
    (select SUM(t1.数量) from t2 as t1 where t1.月份 < MONTH(CURRENT_TIMESTAMP)) as [本月前总累计数量]
    from t2
    where t2.月份 = MONTH(CURRENT_TIMESTAMP)
    group by t2.月份;