产量表(output),表结构如下:  id       date       value  
  1    2012-03-01     6500   
  2    2012-03-02     5800
查询output表,实现如下报表,表头如下:
当日产量     月累计      年累计
期中当日产量列就是output表的value列,月累计列的数据是这样的,比如今天是3月15日,月累计就是指从3月1日到3月15日的产量之和,比如今天是3月16日,月累计就是从3月1日到3月16日的产量之和,该怎么用SQL语句得到月累计的值?年累计也是如此,比如今天是3月15日,年累计就是1月、2月再加上3月15天的产量之和,该怎么用SQL语句实现呢?大家帮帮忙!

解决方案 »

  1.   

    参考 http://hi.baidu.com/linmoug/blog/item/5e3180ec7c35b7db2e2e2179.html
      

  2.   


    --> 测试数据:[ta]
    if object_id('[ta]') is not null drop table [ta]
    go 
    create table [ta]([id] int,[date] datetime,[value] int)
    insert [ta]
    select 1,'2012-03-01',6500 union all
    select 2,'2012-03-02',5800 union all
    select 3,'2012-04-02',10000--------------开始查询--------------------------select [date],
    (select sum([value]) from [ta] where convert(varchar(7),[date],120)=convert(varchar(7),t.[date],120)), 
    (select sum([value]) from [ta] where year([date])=year(t.[date]))
    from [ta] t
    ----------------结果----------------------------
    /* 
    date                                
    ----------------------- ----------- -----------
    2012-03-01 00:00:00.000 12300       22300
    2012-03-02 00:00:00.000 12300       22300
    2012-04-02 00:00:00.000 10000       22300(3 行受影响)
    */
      

  3.   

    借用2楼数据create table [ta]([id] int,[date] datetime,[value] int)
    insert [ta]
    select 1,'2012-03-01',6500 union all
    select 2,'2012-03-02',5800 union all
    select 3,'2012-04-02',10000
    SELECT value,
      (SELECT SUM(Value) FROM ta AS B WHERE B.date >= CAST((LEFT(CONVERT(VARCHAR(10),A.date,23),7) + '-01') AS DATETIME) AND A.date >= B.date) AS MonthValue,
      (SELECT SUM(Value) FROM ta AS C WHERE C.date >= CAST((LEFT(CONVERT(VARCHAR(10),A.date,23),4) + '-01-01') AS DATETIME) AND A.date >= C.date) AS YearValue
    FROM ta AS A
      

  4.   


    结果value MonthValue YearValue
    6500 6500 6500
    5800 12300 12300
    10000 10000 22300
      

  5.   

    select *,
    month=(select sum(value) from ta  where convert(char(7),date,121)=convert(char(7),a.date,121) and date<=a.date),
    year=(select sum(value) from ta  where convert(char(4),date,121)=convert(char(4),a.date,121) and date<=a.date) from ta a
      

  6.   

    谢谢大家了,照着magician547的思路解决了。