有一张基础表:生产日期        产品名称        生产数量
我想按月份统计查询出这样的结构:月份        新产品数量      老产品数量2-2009     24            256
1-2009     7             139
……新产品的筛选是按该产品名称在本月以及之前的日期中第一次出现,视为新产品。在老产品数量的统计中将其扣除。先谢谢了!

解决方案 »

  1.   

    本月以及之前的日期中
    -->>貌似没有交代清楚啊。是本月初到目前得日期还是什么?
      

  2.   

    不知道你究竟想要什么,随便写了一个
    declare @t table (日期 datetime)
    insert @t
    select '2009-1-1'union  
    select '2009-2-1'select distinct 日期, 新产品数量=(select isnull(sum(生产数量),0) from tb where  产品名称=a.产品名称 and convert(varchar(6),t.日期,120)=convert(varchar(6),a.生产日期,120)),
           旧产品数量=(select sum(生产数量) from tb) 
    from @t t left join tb a on convert(varchar(6),t.日期,120)>=convert(varchar(6),a.生产日期,120)
      

  3.   


    create table #1(生产日期 datetime,产品名称 nvarchar(20),生产数量 int)
    insert #1 values('2006-2-17','风机',34)
    insert #1 values('2006-9-3','运轴',187)
    insert #1 values('2007-11-23','风机',13)
    insert #1 values('2008-8-15','卡瓦',24)select 月份
    ,新产品数 = (
    select sum(生产数量) from #1 a where convert(nvarchar(7),生产日期,120) = t.月份 and not exists(select 1 from #1 where 生产日期 < t.月份+'-01' and 产品名称 = a.产品名称)
    )
    ,旧产品数 = (
    select sum(生产数量) from #1 a where convert(nvarchar(7),生产日期,120) = t.月份 and  exists(select 1 from #1 where 生产日期 < t.月份+'-01' and 产品名称 = a.产品名称)
    )
    from 
    (
    select convert(nvarchar(7),生产日期,120) as 月份 
    from #1 t group by convert(nvarchar(7),生产日期,120) 
    )
     t月份      新产品数        旧产品数
    ------- ----------- -----------
    2006-02 34          NULL
    2006-09 187         NULL
    2007-11 NULL        13
    2008-08 24          NULL(4 row(s) affected)
      

  4.   

    9楼的老歌,按你的运行是这样的结果,不对呀。月份      新产品数        旧产品数2006-02 34 NULL
    2006-09 NULL 187
    2007-11 NULL 13
    2008-08 NULL 24
      

  5.   

    问题找到了,是SQL Server 2005中文字符支持的问题。9楼是对的,谢谢!结贴。