最近按需求写了个报表,交叉部分我这样做的 
...... 
...... 
select tabinfo2.daareaname,tabinfo2.areaname,tabinfo2.simplename,tabinfo2.userdef2 as pinpai,tabinfo2.outstockdt,tabinfo2.yewuqi, sum(case tabinfo2.yewuqi when '2008-07' then tabinfo2.fahuoje else 0 end) as '2008-07', 
sum(case tabinfo2.yewuqi when '2008-08' then tabinfo2.fahuoje else 0 end) as '2008-08', 
sum(case tabinfo2.yewuqi when '2008-09' then tabinfo2.fahuoje else 0 end) as '2008-09', 
sum(case tabinfo2.yewuqi when '2008-10' then tabinfo2.fahuoje else 0 end) as '2008-10', 
sum(case tabinfo2.yewuqi when '2008-11' then tabinfo2.fahuoje else 0 end) as '2008-11', 
sum(case tabinfo2.yewuqi when '2008-12' then tabinfo2.fahuoje else 0 end) as '2008-12', 
sum(case tabinfo2.yewuqi when '2009-01' then tabinfo2.fahuoje else 0 end) as '2009-01', 
sum(case tabinfo2.yewuqi when '2009-02' then tabinfo2.fahuoje else 0 end) as '2009-02', 
sum(case tabinfo2.yewuqi when '2009-03' then tabinfo2.fahuoje else 0 end) as '2009-03', 
sum(case tabinfo2.yewuqi when '2009-04' then tabinfo2.fahuoje else 0 end) as '2009-04' 
from ( 
...... 
...... 
按业务期统计发货金额 现在问题来了,我只会固定列数的,每个业务期要给她加一条代码太麻烦,当业务期是变量时,不知道该怎么做,看了例子没看懂, 参考:
http://server.chinabyte.com/474/2591974.shtml 
这个列子是我学到的交叉表的做法。
后来根据‘触发器专家’的提示完成了修改。
select ........... 
into #test
from (
)tabinfo2
.........
declare @sql varchar(8000)
set  @sql = 'select classid,classname, pinpai,daareaname,areaname,simplename,classnamedetail, 'select @sql = @sql + 'sum(case convert(varchar(7),yewuqi,120) when '''+yewuqi+''' then fahuoje else 0 end) as '''+yewuqi+''','from (select distinct convert(varchar(7),yewuqi,120) yewuqi from #test ) as a  
select @sql = left(@sql,len(@sql)-1) + ' from #test group by classid,classname,pinpai,daareaname,areaname,simplename,
classnamedetail,convert(varchar(7),yewuqi,120) '
--tabinfo2.classid,tabinfo2.classname,tabinfo2.userdef2 as pinpai,
--tabinfo2.daareaname,tabinfo2.areaname,tabinfo2.simplename,tabinfo2.classnamedetail,convert(varchar(7),tabinfo2.yewuqi,120)
exec(@sql)drop table #test
现在是根据业务期自动生成每个业务期的发货金额,结果也是对的,
但是现在交叉的业务期部分顺序是乱的,变成:
(前面某些字段)   2009-04  2008-10 2008-07  2009-03   
这个样子,在几个地方加了GROUP BY, ORDER BY都没用,请高手指点。

解决方案 »

  1.   

    主要這句select @sql = @sql + 'sum(case convert(varchar(7),yewuqi,120) when '''+yewuqi+''' then fahuoje else 0 end) as '''+yewuqi+''',' from (select distinct top 100 percent  convert(varchar(7),yewuqi,120) yewuqi from #test order by convert(varchar(7),yewuqi,120) ) as a 
      

  2.   


    拼接完SQL后
    print(@sql) 看一下拼接的SQL中有沒有Order by ,order by 是否在正確的位置上.
      

  3.   

    把select ........... 
    into #test 
    from ( 
    )tabinfo2  order by --按时期排下序试试。
      

  4.   


    也就是说,生成#test的时候,就要按日期从小到大排好序。
      

  5.   

    多谢各位指点。触发器专家,呵呵,刚刚试验了,不行。 用的ORDER BY  yewuqi
    按时期不可能吧,这个业务期本身就是变的,刚2009-06出来了, 下个月又会出2009-07 我不能提前给他排。
    play warcraft 是对的, 
    悄悄的问一句,是玩 war of warcraft 还是 world of warcraft。