学习 SQL 语句 - Select(7): 分组统计之 Avg()、Sum()、Max()、Min()、Count()

时间:2021-05-20 22:54:07
本文来自:万一
Group By

本来 Group By 也可以根据多个字段分组("," 隔开), 但这个例子只有 Continent 字段适合分组,
也只有 Area、Population 字段适合统计.

本例效果图:

学习 SQL 语句 - Select(7): 分组统计之 Avg()、Sum()、Max()、Min()、Count()

代码文件:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, Grids, DBGrids, DB, ADODB;

type
  TForm1 = class(TForm)
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    ADODataSet1: TADODataSet;
    Panel1: TPanel;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT Continent, ' +
                   'AVG(Area) AS 平均面积, AVG(Population) AS 平均人口 ' +
                   'FROM country GROUP BY Continent';
    Open;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT Continent, ' +
                   'SUM(Area) AS 面积总数, SUM(Population) AS 人口总数 ' +
                   'FROM country GROUP BY Continent';
    Open;
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT Continent, ' +
                   'MAX(Area) AS 面积最大, MIN(Population) AS 人口最少 ' +
                   'FROM country GROUP BY Continent';
    Open;
  end;
end;

procedure TForm1.Button4Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT Continent, ' +
                   'MAX(Area + Population) AS 面积与人口总和最多, ' +
                   'MIN(Area + Population) AS 面积与人口总和最少 ' +
                   'FROM country GROUP BY Continent';
    Open;
  end;
end;

procedure TForm1.Button5Click(Sender: TObject);
begin
  with ADODataSet1 do begin
    Close;
    CommandText := 'SELECT COUNT(*) AS 记录总数 FROM country';
    Open;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  mdbFile: string;
begin
  mdbFile := GetEnvironmentVariable('COMMONPROGRAMFILES');
  mdbFile := mdbFile + '\CodeGear Shared\Data\dbdemos.mdb';

  ADODataSet1.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' +
    mdbFile + ';Persist Security Info=False';

  DBGrid1.DataSource := DataSource1;
  DataSource1.DataSet := ADODataSet1;
end;

end.