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

112 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; }
2011-09-26 04:00:46 +00:00
static String name() { return "max"; }
};
struct AggregateFunctionsMinMaxData
{
Field value;
};
2011-09-26 04:00:46 +00:00
/// Берёт минимальное (или максимальное) значение. Если таких много - то первое попавшееся из них.
template <typename Traits>
class AggregateFunctionsMinMax : public IUnaryAggregateFunction<AggregateFunctionsMinMaxData>
2011-09-26 04:00:46 +00:00
{
private:
DataTypePtr type;
public:
String getName() const { return Traits::name(); }
String getTypeID() const { return Traits::name(); }
DataTypePtr getReturnType() const
{
return type;
}
void setArgument(const DataTypePtr & argument)
{
type = argument;
}
void addOne(AggregateDataPtr place, const Field & value_) const
2011-09-26 04:00:46 +00:00
{
Data & d = data(place);
if (!d.value.isNull())
2011-09-26 04:00:46 +00:00
{
if (Traits::better(value_, d.value))
d.value = value_;
2011-09-26 04:00:46 +00:00
}
else
d.value = value_;
2011-09-26 04:00:46 +00:00
}
void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs) const
2011-09-26 04:00:46 +00:00
{
Data & d = data(place);
const Data & d_rhs = data(rhs);
if (!d.value.isNull())
2011-09-26 04:00:46 +00:00
{
if (Traits::better(d_rhs.value, d.value))
d.value = d_rhs.value;
2011-09-26 04:00:46 +00:00
}
else
d.value = d_rhs.value;
2011-09-26 04:00:46 +00:00
}
void serialize(ConstAggregateDataPtr place, WriteBuffer & buf) const
2011-09-26 04:00:46 +00:00
{
type->serializeBinary(data(place).value, buf);
2011-09-26 04:00:46 +00:00
}
void deserializeMerge(AggregateDataPtr place, ReadBuffer & buf) const
2011-09-26 04:00:46 +00:00
{
Data & d = data(place);
if (!d.value.isNull())
2011-09-26 04:00:46 +00:00
{
Field value_;
type->deserializeBinary(value_, buf);
if (Traits::better(value_, d.value))
d.value = value_;
2011-09-26 04:00:46 +00:00
}
else
type->deserializeBinary(d.value, buf);
2011-09-26 04:00:46 +00:00
}
Field getResult(ConstAggregateDataPtr place) const
2011-09-26 04:00:46 +00:00
{
return data(place).value;
2011-09-26 04:00:46 +00:00
}
};
typedef AggregateFunctionsMinMax<AggregateFunctionMinTraits> AggregateFunctionMin;
typedef AggregateFunctionsMinMax<AggregateFunctionMaxTraits> AggregateFunctionMax;
}