ClickHouse/dbms/include/DB/AggregateFunctions/AggregateFunctionsMinMax.h

113 lines
2.2 KiB
C
Raw Normal View History

2011-09-26 04:00:46 +00:00
#pragma once
#include <DB/IO/WriteHelpers.h>
#include <DB/IO/ReadHelpers.h>
#include <DB/AggregateFunctions/IUnaryAggregateFunction.h>
namespace DB
{
struct AggregateFunctionMinTraits
{
static bool better(const Field & lhs, const Field & rhs) { return lhs < rhs; }
static String name() { return "min"; }
};
struct AggregateFunctionMaxTraits
{
static bool better(const Field & lhs, const Field & rhs) { return !(lhs < rhs) && !(lhs == rhs); }
static String name() { return "max"; }
};
/// Берёт минимальное (или максимальное) значение. Если таких много - то первое попавшееся из них.
template <typename Traits>
class AggregateFunctionsMinMax : public IUnaryAggregateFunction
{
private:
bool got;
Field value;
DataTypePtr type;
public:
AggregateFunctionsMinMax() : got(false) {}
String getName() const { return Traits::name(); }
String getTypeID() const { return Traits::name(); }
2011-12-19 08:06:31 +00:00
AggregateFunctionPlainPtr cloneEmpty() const
2011-09-26 04:00:46 +00:00
{
AggregateFunctionsMinMax * res = new AggregateFunctionsMinMax;
res->type = type;
return res;
}
DataTypePtr getReturnType() const
{
return type;
}
void setArgument(const DataTypePtr & argument)
{
type = argument;
}
void addOne(const Field & value_)
{
if (got)
{
if (Traits::better(value_, value))
value = value_;
}
else
{
got = true;
value = value_;
}
}
void merge(const IAggregateFunction & rhs)
{
if (got)
{
2012-09-03 06:32:38 +00:00
Field value_ = static_cast<const AggregateFunctionsMinMax &>(rhs).value;
2011-09-26 04:00:46 +00:00
if (Traits::better(value_, value))
value = value_;
}
else
2012-09-03 06:32:38 +00:00
value = static_cast<const AggregateFunctionsMinMax &>(rhs).value;
2011-09-26 04:00:46 +00:00
}
void serialize(WriteBuffer & buf) const
{
type->serializeBinary(value, buf);
}
void deserializeMerge(ReadBuffer & buf)
{
if (got)
{
Field value_;
type->deserializeBinary(value_, buf);
if (Traits::better(value_, value))
value = value_;
}
else
type->deserializeBinary(value, buf);
}
Field getResult() const
{
return value;
}
};
typedef AggregateFunctionsMinMax<AggregateFunctionMinTraits> AggregateFunctionMin;
typedef AggregateFunctionsMinMax<AggregateFunctionMaxTraits> AggregateFunctionMax;
}