日期:2014-05-18 浏览次数:20559 次
table1 (classid int,pricetime datetime,price money) insert into table1 select 1,'2012-03-01',22 insert into table1 select 1,'2012-03-03',20 insert into table1 select 1,'2012-03-04',20 insert into table1 select 1,'2012-04-06',23 insert into table1 select 1,'2012-04-07',32 select top 6 year(datetime)years,datepart(mm,datetime) months,sum(money) from table1 group by year(datetime),datepart(mm,datetime) order by years desc,months desc
go create table table1( classid int, pricetime datetime, price money ) go insert into table1 select 1,'2012-03-01',22 insert into table1 select 1,'2012-03-03',20 insert into table1 select 1,'2012-03-04',20 insert into table1 select 1,'2012-04-06',23 insert into table1 select 1,'2012-04-07',32 select b.years,b.months,ISNULL(a.price,0) price from( select top 6 year(pricetime)years, datepart(mm,pricetime) months, sum(price) as price from table1 group by year(pricetime),datepart(mm,pricetime) order by years desc,months desc )a right join( select distinct datepart(yy,dateadd(MM,-number,MAX(pricetime))) as years, datepart(mm,dateadd(MM,-number,MAX(pricetime))) as months from table1 cross join master..spt_values where number between -1 and 4 --and type='P' group by number)b on a.years=b.years and a.months=b.months order by 1,2 /* years months price 2011 12 0.00 2012 1 0.00 2012 2 0.00 2012 3 62.00 2012 4 55.00 2012 5 0.00 */ 更改了一下