数据库结构如下
         id       year     month     value
1 2010 10 1
2 2010 11 2
3 2011 1 1
4 2011 2 3条件是当我输入2010年11月-2010年11月
得出表结构的值如下期初   发生数      期末
1        2          3当我输入条件是2010年11月-2011年2月期初   发生数      期末
1        6          7

解决方案 »

  1.   

    select * from tb where year+'-'+'month' between '2010-11' and '2011-10'
      

  2.   


    create table t1
    (
    id int,
    cyear varchar(5),
    cmonth varchar(5),
    ivalue int
    )
    insert into t1
    select 1, '2010', '10', 1 union all
    select 2, '2010', '11', 2 union all
    select 3, '2011', '1', 1 union all
    select 4, '2011', '2', 3;with abc as
    (select *,convert(datetime,cyear+'-'+case when len(cmonth)=1 then '0'+cmonth else cmonth end+'-01') as ddate 
    from t1)
    select a.ivalue as '期初',b.ivalue as '发生数',a.ivalue+b.ivalue as '期末' from abc a inner join
    (select min(b.ddate) as mindate,sum(b.ivalue) as ivalue from abc b where b.ddate>='2010-11-01' and b.ddate<'2011-03-01') b 
    on a.ddate=dateadd(month,-1,b.mindate)