日期:2014-05-18  浏览次数:20410 次

一个时间段如何按月或按年显示
select total from xy where ldate between '2010-10-01' and '2011-02-02'

如上面的数据如何显示成下面:

 (无列名) 2010-10 2010-11 2010-12 2011-01 2011-02
  金额: 100.00 125.00 150.00 150.00 150.00

------解决方案--------------------
create table test1(
ldate char(10),
total numeric(9,2))
go
insert into test1 values('2010-10-01',11)
insert into test1 values('2010-10-12',11)
insert into test1 values('2010-10-21',11)
insert into test1 values('2010-12-01',11.5)
insert into test1 values('2010-12-11',11.5)
insert into test1 values('2010-11-01',11.5)
insert into test1 values('2010-11-11',110)
insert into test1 values('2011-01-01',101)


declare @sql varchar(8000)
set @sql = 'select ''1'' as c '
select @sql = @sql + ', max(case ldate when ''' + ldate+ ''' then total else 0 end) [' + ldate+ ']'
from (select distinct left(ldate,7)as ldate from test1 group by ldate) as a
set @sql = @sql + ' from (select ldate,sum(total) as total from (select left(ldate,7)as ldate,total from test1 ) c group by ldate)d '
print @sql
exec(@sql)