TClientDataSet研究之一:一个分组函数

TClientDataSet是一个非常不错的内存数据集,不仅拥有TDataSet通用的数据集功能,还拥有其独特的查询分组统计功能。
为了表述方便,TClientDataSet简称为CDS。
设置分组功能如下操作:
1、首先,必须建立CDS.IndexDefs索引。直接使用CDS.IndexFieldnames是不行,原因是这种简单的建立索引方式无法使用GroupingLevel 属性。
2、设置Aggregates。
3、激活Aggregates。
下面是一个例子,比如,我们希望对某个数据集的字段进行分组显示,方法很多,但我们不希望再去从后台数据库查询,希望充分利用现有的CDS数据集进行分组,并将其结果集添加到TStrings(如TCombobox的Items)。
function GetGroupName(cdsData: TClientDataSet;
const GroupName: string; GroupList: TStrings): Integer;
var
CDS: TClientDataSet;
sIndexName: string;
begin
Result := -1;

CDS := TClientDataSet.Create(nil);
try
     CDS.DisableControls;

     sIndexName := 'cds_Index_' + GroupName;
     if not cdsData.Active then
       Exit;
     CDS.Data := cdsData.Data; //复制数据,避免建立索引与原有数据集冲突

     with CDS.IndexDefs.AddIndexDef do
     begin
       Name := sIndexName;
       Fields := GroupName;
       GroupingLevel := 1; //非常重要的属性
     end;
     CDS.IndexName := sIndexName;//当前使用索引

     with CDS.Aggregates.Add do
     begin
       GroupingLevel := 1;
       IndexName := sIndexName;
       Visible := False;
       Active := True;
     end;
     CDS.AggregatesActive := True;
     GroupList.Clear;
     GroupList.Add('');

     CDS.First;
     Result := 0;
     while not CDS.Eof do
     begin
       if gbFirst in CDS.GetGroupState(1) then
       begin
         GroupList.Add(CDS.FieldByName(GroupName).AsString);
         Inc(Result);
       end;
       CDS.Next;
     end;

finally
     CDS.EnableControls;
     CDS.Free;
end;

end;

        
        



        







        
          
            
            评论这张
          
        


          
            
               TClientDataSet研究之一:一个分组函数 - yyimen - yyimen的博客
            
            转发至微博
          
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值