Ir para conteúdo
  • Cadastre-se

dev botao

Campos aggregate em rumtime no clientdataset


  • Este tópico foi criado há 2507 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.

Recommended Posts

Compartilhando essa classe que achei no site do Marcos Salles, pra quem gosta de usar campos aggregate no DataSet, essa função é uma mão na roda pois não precisamos mais cria-los, só chamar a função e passar o campo que queremos totalizar.

--

unit UTypeAggregate;

//https://marcosalles.wordpress.com/2011/01/30/criacao-de-campos-aggregates-rumtime-clientdataset/

interface

uses DBClient, SysUtils;

Type
  TypeAggregateERROR = class(Exception);

  TAggregateRetorne = (ftSomar,ftMaxima,ftContar,FtMedia);

  TOperacoes =class
    class function  Retornar(ClientDataSet:TClientDataSet; Const cField:String; Tipo:TAggregateRetorne):String;
  end;

implementation

{ TOperacoes }

class function TOperacoes.Retornar(ClientDataSet: TClientDataSet; const cField: String; Tipo: TAggregateRetorne): String;
begin

  try
    //ATENÇÃO: NÃO DEIXE O CAMPO TRAZER VALORES NULO NA PESQUISA DO SQL, ERRO NO CALCULO
    with ClientDataSet do
    begin
      case Tipo of
        ftSomar:
        begin
          AggregatesActive := False;

          if Aggregates.Find('SOMAR_'+ cField) = nil then
            with Aggregates.Add do
            begin
              Expression    := 'Sum('+cField+')';
              AggregateName := 'SOMAR_'+ cField;
              Active        := True;
            end;
          AggregatesActive := True;
          Result := Aggregates.Find('SOMAR_'+ cField).Value;
        end;
        ftMaxima:
        begin
          AggregatesActive := False;
          if Aggregates.Find('MAXIMA_'+ cField) = nil then
            with Aggregates.Add do
            begin
              Expression    := 'Max('+cField+')';
              AggregateName := 'MAXIMA_'+ cField;
              Active        := True;
            end;
          AggregatesActive := True;
          Result := Aggregates.Find('MAXIMA_'+ cField).Value;
        end;
        ftContar:
        begin
          AggregatesActive := False;
          if Aggregates.Find('CONTAR_'+ cField) = nil then
            with Aggregates.Add do
            begin
              Expression    := 'Count('+cField+')';
              AggregateName := 'CONTAR_'+ cField;
              Active        := True;
            end;
          AggregatesActive := True;
          Result := Aggregates.Find('CONTAR_'+ cField).Value;
        end;
        ftMedia:
        begin
          AggregatesActive := False;
          if Aggregates.Find('MEDIA_'+ cField) = nil then
            with Aggregates.Add do
            begin
              Expression    := 'Avg('+cField+')';
              AggregateName := 'MEDIA_'+ cField;
              Active        := True;
            end;
          AggregatesActive := True;
          Result := Aggregates.Find('MEDIA_'+ cField).Value;
        end;
      end;
    end;

  except
    on e:Exception do
      raise TypeAggregateERROR.Create('Erro na Totalização.'+sLineBreak+
                                      'Verifique se o campo contém valores NULO ou se o DataSet esta inativo'+ sLineBreak+
                                      E.Message);
  end;
end;

end.

Ex:
    FSUB_TOTAL_A := StrToFloatDef(TOperacoes.Retornar(cdsItensRateio, cdsItensRateioVALOR_TOTAL_A.FieldName, ftSomar), 0);
    FSUB_TOTAL_B := StrToFloatDef(TOperacoes.Retornar(cdsItensRateio, cdsItensRateioVALOR_TOTAL_B.FieldName, ftSomar), 0);
 

 

Analysis and System Development - Delphi Programmer - Computer Technician - Developing solutions together

 

Link para o comentário
Compartilhar em outros sites

  • Este tópico foi criado há 2507 dias atrás.
  • Talvez seja melhor você criar um NOVO TÓPICO do que postar uma resposta aqui.

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora
×
×
  • Criar Novo...

Informação Importante

Colocamos cookies em seu dispositivo para ajudar a tornar este site melhor. Você pode ajustar suas configurações de cookies, caso contrário, assumiremos que você está bem para continuar.