//先在窗体上放置 ClientDataSet1、Button1 然后:
{ 建表 }
procedure TForm1.FormCreate(Sender: TObject);
begin
with ClientDataSet1 do begin
{ 定义表 }
FieldDefs.Add('班级', ftWideString, 4);
FieldDefs.Add('姓名', ftWideString, 8);
FieldDefs.Add('年龄', ftByte);
FieldDefs.Add('语文成绩', ftFloat);
FieldDefs.Add('数学成绩', ftFloat);
{ 建立表 }
CreateDataSet;
{ 添加 18 条测试数据 }
AppendRecord(['一班', '赵钱', 8, 81, 98]);
AppendRecord(['一班', '孙李', 9]); { 假如他没有成绩 }
AppendRecord(['一班', '周吴', 8, 82, 97]);
AppendRecord(['三班', '郑王', 9, 83, 96]);
AppendRecord(['三班', '冯陈', 8, 84, 95]);
AppendRecord(['三班', '诸卫', 9, 85, 94]);
AppendRecord(['二班', '蒋沈', 8, 86, 93]);
AppendRecord(['二班', '韩杨', 9, 87, 92]);
AppendRecord(['二班', '朱秦', 8, 88, 91]);
AppendRecord(['一班', '尤许', 9, 89, 90]);
AppendRecord(['一班', '何吕', 8, 99, 89]);
AppendRecord(['一班', '施张', 9, 98, 88]);
AppendRecord(['三班', '孔曹', 8, 97, 87]);
AppendRecord(['三班', '严华', 9, 96, 86]);
AppendRecord(['三班', '金魏', 8, 95, 85]);
AppendRecord(['二班', '陶姜', 9, 94, 84]);
AppendRecord(['二班', '戚谢', 8, 93, 83]);
AppendRecord(['二班', '邹喻', 9, 92, 82]);
end;
{ 备份这些数据给后面测试用 }
ClientDataSet1.MergeChangeLog;
ClientDataSet1.SaveToFile('C:\Temp\Test.xml', dfXMLUTF8);
end;
{ 统计 }
procedure TForm1.Button1Click(Sender: TObject);
begin
{ (有效的)人员总数 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Count(语文成绩)';
Active := True;
end;
{ 语文总成绩 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Sum(语文成绩)';
Active := True;
end;
{ 语文平均成绩 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Avg(语文成绩)';
Active := True;
end;
{ 语文最高成绩 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Max(语文成绩)';
Active := True;
end;
{ 语文最低成绩 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Min(语文成绩)';
Active := True;
end;
{ 语文和数学的总成绩 }
with ClientDataSet1.Aggregates.Add do begin
Expression := 'Sum(语文成绩) + Sum(数学成绩)';
Active := True;
end;
{ 执行统计 }
ClientDataSet1.AggregatesActive := True;
{ 查看统计结果 }
with ClientDataSet1 do begin
ShowMessageFmt('%d', [Integer(Aggregates[0].Value)]); { 17 }
ShowMessageFmt('%.2f', [Double(Aggregates[1].Value)]); { 1529.00 }
ShowMessageFmt('%.2f', [Double(Aggregates[2].Value)]); { 89.94 }
ShowMessageFmt('%.2f', [Double(Aggregates[3].Value)]); { 99.00 }
ShowMessageFmt('%.2f', [Double(Aggregates[4].Value)]); { 81.00 }
ShowMessageFmt('%.2f', [Double(Aggregates[5].Value)]); { 3059.00 }
end;
end;
设计时使用统计的过程(使用了上面的测试值):