表结构:
列: 录入时间 ,AA ,BB
2006/01/01 1 2
2006/01/02 3 4
2006/01/03 5 6
2006/01/30 100 111
想得到:
时间,01/01AA,01/01BB,01/02AA,01/02BB,01/03AA,01/03BB ......01/31AA,01/31BB 2006/01,1, 2, 3, 4, 5, 6, ,NULL,NULL,......NULL,100,111意思就是把一个月的数据屏开,
不一定是1月的.也可以是2月的,3月的......(作为查询条件)
如果是2006年2月的话就到02/28BB为此(要算出这个月的天数来决定列的数)
列: 录入时间 ,AA ,BB
2006/01/01 1 2
2006/01/02 3 4
2006/01/03 5 6
2006/01/30 100 111
想得到:
时间,01/01AA,01/01BB,01/02AA,01/02BB,01/03AA,01/03BB ......01/31AA,01/31BB 2006/01,1, 2, 3, 4, 5, 6, ,NULL,NULL,......NULL,100,111意思就是把一个月的数据屏开,
不一定是1月的.也可以是2月的,3月的......(作为查询条件)
如果是2006年2月的话就到02/28BB为此(要算出这个月的天数来决定列的数)
create table t(录入时间 datetime,AA int,BB int)
insert into t select '2006/01/01',1 ,2
insert into t select '2006/01/02',3 ,4
insert into t select '2006/01/03',5 ,6
insert into t select '2006/01/30',100,111
--生成临时表及中间数据
set rowcount 1000
select identity(int,0,1) as num into # from sysobjects,syscolumns
set rowcount 0--定义变量
declare @s varchar(8000)
declare @sdate char(7),@edate char(7)
set @sdate='2006/01'
set @edate='2006/01'--组织动态SQL
set @s='select 时间=convert(char(7),录入时间,111)'select
@s=@s+',['+right(a.dt,5)+'AA]=max(case 录入时间 when '''+a.dt+''' then AA end)'
+',['+right(a.dt,5)+'BB]=max(case 录入时间 when '''+a.dt+''' then BB end)'
from
(select convert(char(10),dateadd(dd,num,cast(@sdate+'/01' as datetime)),111) as dt from #) a
where
left(a.dt,7) between @sdate and @edateset @s=@s+' from t group by convert(char(7),录入时间,111)'--执行动态SQL,结果自己看
exec(@s)--删除测试数据
drop table t,#
insert tbtb
select '2006/01/01',1,2 union all
select '2006/01/02',3,4 union all
select '2006/01/03',5,6 union all
select '2006/01/30',100,111--select distinct lrtime from tbtb full join select (select 'aa' as col union all select 'bb') b
declare @sql varchar(8000)
set @sql = ''select @sql = @sql + ',['+right(lrtime,5)+'AA]=sum(case when lrtime = '''+lrtime+''' then aa end)'+
',['+right(lrtime,5)+'BB]=sum(case when lrtime = '''+lrtime+''' then bb end)'
from (select distinct lrtime from tbtb ) a
--print @sql
exec('select left(lrtime,7) as 时间'+@sql+ ' from tbtb group by left(lrtime,7)')
drop table tbtb 时间 01/01AA 01/01BB 01/02AA 01/02BB 01/03AA 01/03BB 01/30AA 01/30BB
---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
2006/01 1 2 3 4 5 6 100 111
如果我有几个月的数据的话你的也来也是几个月的..