#pragma once #include #include #include #include namespace DB { template struct AggregateFunctionAvgData { T sum; UInt64 count; AggregateFunctionAvgData() : sum(0), count(0) {} }; /// Считает арифметическое среднее значение чисел. template class AggregateFunctionAvg final : public IUnaryAggregateFunction::Type>, AggregateFunctionAvg > { public: String getName() const override { return "avg"; } DataTypePtr getReturnType() const override { return new DataTypeFloat64; } void setArgument(const DataTypePtr & argument) override { if (!argument->isNumeric()) throw Exception("Illegal type " + argument->getName() + " of argument for aggregate function " + getName(), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } void addOne(AggregateDataPtr place, const IColumn & column, size_t row_num) const { this->data(place).sum += static_cast &>(column).getData()[row_num]; ++this->data(place).count; } void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs) const override { this->data(place).sum += this->data(rhs).sum; this->data(place).count += this->data(rhs).count; } void serialize(ConstAggregateDataPtr place, WriteBuffer & buf) const override { writeBinary(this->data(place).sum, buf); writeVarUInt(this->data(place).count, buf); } void deserializeMerge(AggregateDataPtr place, ReadBuffer & buf) const override { typename NearestFieldType::Type tmp_sum = 0; UInt64 tmp_count = 0; readBinary(tmp_sum, buf); readVarUInt(tmp_count, buf); this->data(place).sum += tmp_sum; this->data(place).count += tmp_count; } void insertResultInto(ConstAggregateDataPtr place, IColumn & to) const override { static_cast(to).getData().push_back( static_cast(this->data(place).sum) / this->data(place).count); } }; }