2011-09-26 04:00:46 +00:00
|
|
|
#pragma once
|
|
|
|
|
2017-04-01 09:19:00 +00:00
|
|
|
#include <IO/WriteHelpers.h>
|
|
|
|
#include <IO/ReadHelpers.h>
|
2011-09-26 04:00:46 +00:00
|
|
|
|
2017-04-01 09:19:00 +00:00
|
|
|
#include <DataTypes/DataTypesNumber.h>
|
|
|
|
#include <Columns/ColumnsNumber.h>
|
2011-09-26 04:00:46 +00:00
|
|
|
|
2017-12-20 07:36:30 +00:00
|
|
|
#include <AggregateFunctions/IAggregateFunction.h>
|
2011-09-26 04:00:46 +00:00
|
|
|
|
|
|
|
|
|
|
|
namespace DB
|
|
|
|
{
|
|
|
|
|
|
|
|
|
2013-06-25 14:16:16 +00:00
|
|
|
template <typename T>
|
2013-02-08 19:34:44 +00:00
|
|
|
struct AggregateFunctionAvgData
|
2011-09-26 04:00:46 +00:00
|
|
|
{
|
2017-04-01 07:20:54 +00:00
|
|
|
T sum = 0;
|
|
|
|
UInt64 count = 0;
|
2013-02-08 19:34:44 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
2017-03-09 00:56:38 +00:00
|
|
|
/// Calculates arithmetic mean of numbers.
|
2013-02-08 19:34:44 +00:00
|
|
|
template <typename T>
|
2017-12-20 07:36:30 +00:00
|
|
|
class AggregateFunctionAvg final : public IAggregateFunctionDataHelper<AggregateFunctionAvgData<typename NearestFieldType<T>::Type>, AggregateFunctionAvg<T>>
|
2013-02-08 19:34:44 +00:00
|
|
|
{
|
|
|
|
public:
|
2017-04-01 07:20:54 +00:00
|
|
|
String getName() const override { return "avg"; }
|
|
|
|
|
|
|
|
DataTypePtr getReturnType() const override
|
|
|
|
{
|
|
|
|
return std::make_shared<DataTypeFloat64>();
|
|
|
|
}
|
|
|
|
|
2017-12-20 07:36:30 +00:00
|
|
|
void add(AggregateDataPtr place, const IColumn ** columns, size_t row_num, Arena *) const override
|
2017-04-01 07:20:54 +00:00
|
|
|
{
|
2017-12-20 07:36:30 +00:00
|
|
|
this->data(place).sum += static_cast<const ColumnVector<T> &>(*columns[0]).getData()[row_num];
|
2017-04-01 07:20:54 +00:00
|
|
|
++this->data(place).count;
|
|
|
|
}
|
|
|
|
|
2017-12-01 21:51:50 +00:00
|
|
|
void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs, Arena *) const override
|
2017-04-01 07:20:54 +00:00
|
|
|
{
|
|
|
|
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 deserialize(AggregateDataPtr place, ReadBuffer & buf, Arena *) const override
|
|
|
|
{
|
|
|
|
readBinary(this->data(place).sum, buf);
|
|
|
|
readVarUInt(this->data(place).count, buf);
|
|
|
|
}
|
|
|
|
|
|
|
|
void insertResultInto(ConstAggregateDataPtr place, IColumn & to) const override
|
|
|
|
{
|
|
|
|
static_cast<ColumnFloat64 &>(to).getData().push_back(
|
|
|
|
static_cast<Float64>(this->data(place).sum) / this->data(place).count);
|
|
|
|
}
|
2017-09-17 20:22:39 +00:00
|
|
|
|
|
|
|
const char * getHeaderFilePath() const override { return __FILE__; }
|
2011-09-26 04:00:46 +00:00
|
|
|
};
|
|
|
|
|
2013-06-13 20:30:47 +00:00
|
|
|
|
2011-09-26 04:00:46 +00:00
|
|
|
}
|