#pragma once #include #include #include #include #include #include namespace DB { template struct AggregateFunctionUniqTraits; template <> struct AggregateFunctionUniqTraits { static UInt64 hash(UInt64 x) { return x; } }; template <> struct AggregateFunctionUniqTraits { static UInt64 hash(Int64 x) { return x; } }; template <> struct AggregateFunctionUniqTraits { static UInt64 hash(Float64 x) { UInt64 res = 0; memcpy(reinterpret_cast(&res), reinterpret_cast(&x), sizeof(x)); return res; } }; template <> struct AggregateFunctionUniqTraits { /// Имейте ввиду, что вычисление приближённое. static UInt64 hash(const String & x) { return CityHash64(x.data(), x.size()); } }; struct AggregateFunctionUniqData { UniquesHashSet set; }; /// Приближённо вычисляет количество различных значений. template class AggregateFunctionUniq : public IUnaryAggregateFunction { public: AggregateFunctionUniq() {} String getName() const { return "uniq"; } String getTypeID() const { return "uniq_" + TypeName::get(); } DataTypePtr getReturnType() const { return new DataTypeUInt64; } void setArgument(const DataTypePtr & argument) { } void addOne(AggregateDataPtr place, const Field & value) const { data(place).set.insert(AggregateFunctionUniqTraits::hash(get(value))); } void merge(AggregateDataPtr place, ConstAggregateDataPtr rhs) const { data(place).set.merge(data(rhs).set); } void serialize(ConstAggregateDataPtr place, WriteBuffer & buf) const { data(place).set.write(buf); } void deserializeMerge(AggregateDataPtr place, ReadBuffer & buf) const { UniquesHashSet tmp_set; tmp_set.read(buf); data(place).set.merge(tmp_set); } Field getResult(ConstAggregateDataPtr place) const { return data(place).set.size(); } }; }