設計時實現的分組統計:
查看原圖(大圖)
運行時實現的分組統計:
//前期只需要添加 ClIEntDataSet1、DataSource1、DBGrid1; 事件只需要關聯窗體的 OnCreate
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, DB, DBClIEnt;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
DataSource1: TDataSource;
ClientDataSet1: TClIEntDataSet;
procedure FormCreate(Sender: TObject);
private
procedure OnGetText_Agg1(Sender: TFIEld; var Text: string;
DisplayText: Boolean);
procedure OnGetText_Agg2(Sender: TFIEld; var Text: string;
DisplayText: Boolean);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
{ 關聯數據控件 }
DBGrid1.DataSource := DataSource1;
DataSource1.DataSet := ClIEntDataSet1;
{ 先打開前面例子中留下的測試文件 }
ClIEntDataSet1.LoadFromFile('C:\Temp\Test.XML');
{ 添加索引, 其中分組級別是 2 }
ClIEntDataSet1.AddIndex('Index1', '班級;年齡', [], '', '', 2);
{ 給數據集指定此索引 }
ClIEntDataSet1.IndexName := 'Index1';
{ 數據結構變化時一般需要先關閉數據集 }
ClIEntDataSet1.Close;
{ 添加統計字段 Agg1: 按班分組統計語文總成績 }
with TAggregateFIEld.Create(Self) do begin
FIEldName := 'Agg1';
Expression := 'Sum(語文成績)';
IndexName := 'Index1';
GroupingLevel := 1;
Active := True;
OnGetText := OnGetText_Agg1;
DataSet := ClIEntDataSet1;
end;
{ 添加統計字段 Agg2: 各班分別按年齡分組統計語文總成績 }
with TAggregateFIEld.Create(Self) do begin
FIEldName := 'Agg2';
Expression := 'Sum(語文成績)';
IndexName := 'Index1';
GroupingLevel := 2;
Active := True;
OnGetText := OnGetText_Agg2;
DataSet := ClIEntDataSet1;
end;
{ 需要在 DBGrid 中顯示的字段 }
with DBGrid1.Columns do begin
Add.FIEldName := '班級';
Add.FIEldName := '姓名';
Add.FIEldName := '年齡';
Add.FIEldName := '語文成績';
Add.FIEldName := 'Agg1';
Add.FIEldName := 'Agg2';
end;
{ 打開數據集並激活統計 }
ClIEntDataSet1.Open;
ClIEntDataSet1.AggregatesActive := True;
end;
procedure TForm1.OnGetText_Agg1(Sender: TFIEld; var Text: string; DisplayText: Boolean);
begin
if gbLast in ClIEntDataSet1.GetGroupState(1) then
Text := Sender.AsString else Text := '';
end;
procedure TForm1.OnGetText_Agg2(Sender: TFIEld; var Text: string; DisplayText: Boolean);
begin
if gbLast in ClIEntDataSet1.GetGroupState(2) then
Text := Sender.AsString else Text := '';
end;
end.