小弟用VB查询SQL2000数据库中数据,然后写入EXCEl表中。
SQL数据库表名为PP,表结构如下:
编码 数值 时间
  A  0.2 5月4日
  B  0.1 5月4日
  C  0.5 5月4日
  D  1.1 5月4日
  E . .
  F . .
  A  0.5 5月6日
  B  0.8 5月6日
  C  2.5 5月6日
  D  0.1 5月6日
  . . .
  . . .
  A  8   5月9日
  B  1.1 5月9日
  C  5   5月9日
  D  6.0 5月9日
  . . .
  . . .
  . . .根据时间条件用select语句查询后结果是:
编码 总和 数值 数值 数值 ...
  A   8.7  0.2  0.5  8 ...
  B   2.0  0.1  0.8 1.1 ...
  C   8    0.5  2.5  5 ...   
  D   7.2  1.1  0.1  6 ...
  E
  F
  . (同一编码的数值,放在一行)

解决方案 »

  1.   

    按编码GROUP BY 就可以了啊
      

  2.   

    --这样将一个月的值做行列转换,可能会超过SQL允许的一个查询语句4000个字符的上限,
    select 编码, sum(数值) as 总和, 
      sum(case when 数值 = '5月4日' then 数值 else 0 ) as 数值_5月4日,
      sum(case when 数值 = '5月6日' then 数值 else 0 ) as 数值_5月6日,
      ... from PP
    group by 编码
      

  3.   

    引用
    http://tech.it168.com/db/s/2006-07-31/200607311324786.shtml注:有2005版本以上的pivot函数使用方法,也有动态转换方法,
      

  4.   

    --用于:交叉表的列数是不确定的
    declare @sql varchar(8000)
    set @sql = 'select name,'select @sql = @sql + 'sum(case subject when '''+subject+'''
    then source else 0 end) as '''+subject+''','
    from (select distinct subject from test) as aselect @sql = left(@sql,len(@sql)-1) + ' from test group by name'exec(@sql)go