我有两个表一个,
学生和教师信息表Information,字段为teachername,studentID,exercise 三个字段,学生表student字段为studentID,Studentname;
现在我要根据这两个表在DBgrid中生列为教师名,学生1exercise数,学生2exercise数,学生3exercise数
现在我已经用下面的代码在DBgrid中生成了动态列,但在计算某个教师相对应的学生的作业总数时,根本就不能把这个数在DBgrid显示在与它所对应学生exercise数列的下面
var
   str: String;
   Customersrv : String;
   col : TColumn;
    i: integer;
Begin
 
 With DBGrid1 Do
  Begin
    Columns.Clear;
      col := Columns.Add;
    col.FieldName := 'teacherName';
    col.Title.Caption := '教师';
 For i:=1 to frmResponse.cBoxResponseType.Items.Count-1 Do
    Begin      col := Columns.Add;
      col.FieldName := 'student'+inttostr(i);
      col.Title.Caption :=QueryMobileResponseType.Fieldbyname('StudentName').AsString;
       QueryMobileResponseType.Next;
             End;
  End;  With QueryInformation  do
  Begin
    For i:=1 to frmResponse.cBoxResponseType.Items.Count-1 Do
    Begin
     str :=' select teachername,studentID,count(teachername) as student'+inttostr(i)+'  from Information  group by teachername,studentID';     End;
    Close;
    sql.clear;
    sql.add(str);
    Open;
  End;

解决方案 »

  1.   

    交叉表  直接写sql 语句实现  参考msdn把
      

  2.   

    Information 表记录是怎么样的??
    是否这样:
    teachername,studentID,exercise 
    李老师       1001      3
    李老师       1002      5
    李老师       1003      8
      

  3.   

    你有QQ吗?能不能把你的QQ给我
      

  4.   

    是这样的结果吧老师名  学生ID1  学生ID2  学生ID3...
    李老师  5        7        9是吧?
      

  5.   

    想不到这么久没碰 Delphi ,忘掉很多
    连 Query1.open 我都想了好半天。  惭愧啊。
    本来是想用 case when 来做,老是语法报错,真是奇怪了,我一直都这么用的
    搞了半天,终于搞出个能出结果的版本出来,楼主验证一下query1.Close;
      query1.SQL.Clear;
      query1.SQL.Add('select Teachername 教师名,');
      query1.SQL.Add('(select sum(exercise) from Information where studentid=''1001''  ) 张三 ,');
      query1.SQL.Add('(select sum(exercise) from Information where studentid=''1002''  ) 李四, ');
      query1.SQL.Add('(select sum(exercise) from Information where studentid=''1003''  ) 王五 ');
      query1.SQL.Add(' from Information a,student b  group by Teachername ');
      query1.Open;
      

  6.   

    楼主说 studentid 是动态生成的,又改了一下,应该没问题了StrSql:='select Teachername 教师名,';   query1.Close;
      query1.SQL.Clear;
      query1.SQL.Add('select studentid,studentname from student ');
      query1.Open;  query1.First;
      while not query1.Eof do
      begin
        StrSql:=StrSql+'(select sum(exercise) from Information where studentid='''
                +query1.Fieldbyname('studentid').AsString+''') '
                +query1.fieldbyname('studentname').AsString+',';
        query1.Next;
      end;
      StrSql:=copy(StrSql,1,length(StrSql)-1); //去掉最后一个逗号
      StrSql:=StrSql+' from Information group by Teachername ';  query1.Close;
      query1.SQL.Clear;
      query1.SQL.Add(StrSql);
      query1.Open;OK,测试通过。我吃饭去了,饿死了
      

  7.   

    上面那个算法,算出来的应该统计的是学生的exercise,而没有和老师关联起来把?
      

  8.   

    但是我得到的记录却是:
    教师名 张三  李四  王五
    李老师 5     6     7
    程老师 5     6     7
    及所有老师得到的学生作业相同啊?
    好像group by 还不行