表结构
商品   日期          数量
A      2010-9-10      10
A      2010-8-11      12
B      2010-9-1       10
A      2010-7-20      30求截止到2010-9月时,销售月份数及数量总计
商品   销售月份数     数量总计
A        2             52
B        1             10
谢谢

解决方案 »

  1.   

    create table #P
    (
      商品 char(2),
      日期 datetime,
      数量 int
    )
    insert into #p select 'A','2010-9-10',10
    union all select 'A','2010-8-11',12
    union all select 'B','2010-9-1',10
    union all select 'A','2010-7-20',30select 商品,count(日期) 日期,sum(数量) 数量
    from #p
    where 日期<='2010-9-1'
    group by 商品商品   日期          数量
    ---- ----------- -----------
    A    2           42
    B    1           10(2 行受影响)
      

  2.   

    这样比较严谨
    count(distinct(convert(varchar(7),日期,120))
      

  3.   

    if OBJECT_ID('tb') is not null
    drop table tb 
    go
    create table tb(商品 varchar(2),日期 date,数量 int)
    insert into tb
    select 'A', '2010-9-10', 10 union all
    select 'A', '2010-8-11', 12 union all
    select 'B', '2010-9-1' ,10 union all
    select 'A', '2010-7-20', 30select 商品,COUNT(distinct CONVERT(varchar(7),日期,120)) as 销售月份数, SUM(数量) as 数量总计
    from tb
    where CONVERT(varchar(7),日期,120)<='2010-09'
    group by 商品商品 销售月份数 数量总计
    A 3 52
    B 1 10
      

  4.   


    select 商品,count(month(日期)) as 月份数,sum(数量) as 数量总计
    from tb
    where convert(varchar(7),日期,120) <='2010-09'
    group by 商品
      

  5.   

    谢水哥
    create table #P
    (
      商品 char(2),
      日期 datetime,
      数量 int
    )
    insert into #p select 'A','2010-9-10',10
    union all select 'A','2010-8-11',12
    union all select 'B','2010-9-1',10
    union all select 'A','2010-7-20',30select 商品,count(distinct(convert(varchar(7),日期,120))) 日期,sum(数量) 数量
    from #p
    where 日期<='2010-10-1'
    group by 商品商品   日期          数量
    ---- ----------- -----------
    A    3           52
    B    1           10(2 行受影响)
      

  6.   

    create table #P
    (
      商品 char(2),
      日期 datetime,
      数量 int
    )
    insert into #p select 'A','2010-9-10',10
    union all select 'A','2010-8-11',12
    union all select 'B','2010-9-1',10
    union all select 'A','2010-7-20',30select 商品,(case when datediff(month,min(日期),'2010-9-1')=0 then 1 else datediff(month,min(日期),'2010-9-1') end) 日期,sum(数量) 数量 from #P
    group by 商品商品   日期          数量
    ---- ----------- -----------
    A    2           52
    B    1           10(2 行受影响)