43 mFilterExpression = parameters.
filter;
67 context = context ? context : &defaultContext;
69 std::unique_ptr<QgsExpression> expression;
79 if ( expression->hasParserError() || !expression->prepare( context ) )
81 mLastError = !expression->parserErrorString().isEmpty() ? expression->parserErrorString() : expression->evalErrorString();
90 lst = expression->referencedColumns();
92 bool expressionNeedsGeometry { expression &&expression->needsGeometry() };
94 if ( !mOrderBy.empty() )
99 if ( orderBy.expression().needsGeometry() )
101 expressionNeedsGeometry =
true;
107 request.
setFlags( expressionNeedsGeometry ?
110 .setSubsetOfAttributes( lst, mLayer->
fields() );
115 if ( !mFilterExpression.isEmpty() )
123 QVariant::Type resultType = QVariant::Double;
130 resultType = QVariant::UserType;
135 bool foundFeatures =
false;
137 if ( !foundFeatures )
141 return defaultValue( aggregate );
144 resultType = std::get<0>( returnType );
145 userType = std::get<1>( returnType );
146 if ( resultType == QVariant::Invalid )
190 resultType = v.type();
191 userType = v.userType();
199 return calculate( aggregate, fit, resultType, userType, attrNum, expression.get(), mDelimiter, context, ok, &mLastError );
204 const QString normalized =
string.trimmed().toLower();
209 if ( normalized == QLatin1String(
"count" ) )
211 else if ( normalized == QLatin1String(
"count_distinct" ) )
213 else if ( normalized == QLatin1String(
"count_missing" ) )
215 else if ( normalized == QLatin1String(
"min" ) || normalized == QLatin1String(
"minimum" ) )
217 else if ( normalized == QLatin1String(
"max" ) || normalized == QLatin1String(
"maximum" ) )
219 else if ( normalized == QLatin1String(
"sum" ) )
221 else if ( normalized == QLatin1String(
"mean" ) )
223 else if ( normalized == QLatin1String(
"median" ) )
225 else if ( normalized == QLatin1String(
"stdev" ) )
227 else if ( normalized == QLatin1String(
"stdevsample" ) )
229 else if ( normalized == QLatin1String(
"range" ) )
231 else if ( normalized == QLatin1String(
"minority" ) )
233 else if ( normalized == QLatin1String(
"majority" ) )
235 else if ( normalized == QLatin1String(
"q1" ) )
237 else if ( normalized == QLatin1String(
"q3" ) )
239 else if ( normalized == QLatin1String(
"iqr" ) )
241 else if ( normalized == QLatin1String(
"min_length" ) )
243 else if ( normalized == QLatin1String(
"max_length" ) )
245 else if ( normalized == QLatin1String(
"concatenate" ) )
247 else if ( normalized == QLatin1String(
"concatenate_unique" ) )
249 else if ( normalized == QLatin1String(
"collect" ) )
251 else if ( normalized == QLatin1String(
"array_agg" ) )
265 return QObject::tr(
"count" );
267 return QObject::tr(
"count distinct" );
269 return QObject::tr(
"count missing" );
271 return QObject::tr(
"minimum" );
273 return QObject::tr(
"maximum" );
275 return QObject::tr(
"sum" );
277 return QObject::tr(
"mean" );
279 return QObject::tr(
"median" );
281 return QObject::tr(
"standard deviation" );
283 return QObject::tr(
"standard deviation (sample)" );
285 return QObject::tr(
"range" );
287 return QObject::tr(
"minority" );
289 return QObject::tr(
"majority" );
291 return QObject::tr(
"first quartile" );
293 return QObject::tr(
"third quartile" );
295 return QObject::tr(
"inter quartile range" );
297 return QObject::tr(
"minimum length" );
299 return QObject::tr(
"maximum length" );
301 return QObject::tr(
"concatenate" );
303 return QObject::tr(
"collection" );
305 return QObject::tr(
"array aggregate" );
307 return QObject::tr(
"concatenate (unique)" );
318 QStringLiteral(
"count" ),
319 QCoreApplication::tr(
"Count" ),
320 QSet<QVariant::Type>()
321 << QVariant::DateTime
325 << QVariant::LongLong
326 << QVariant::ULongLong
331 QStringLiteral(
"count_distinct" ),
332 QCoreApplication::tr(
"Count Distinct" ),
333 QSet<QVariant::Type>()
334 << QVariant::DateTime
338 << QVariant::LongLong
339 << QVariant::ULongLong
344 QStringLiteral(
"count_missing" ),
345 QCoreApplication::tr(
"Count Missing" ),
346 QSet<QVariant::Type>()
347 << QVariant::DateTime
351 << QVariant::LongLong
356 QStringLiteral(
"min" ),
357 QCoreApplication::tr(
"Min" ),
358 QSet<QVariant::Type>()
359 << QVariant::DateTime
363 << QVariant::LongLong
364 << QVariant::ULongLong
370 QStringLiteral(
"max" ),
371 QCoreApplication::tr(
"Max" ),
372 QSet<QVariant::Type>()
373 << QVariant::DateTime
377 << QVariant::LongLong
378 << QVariant::ULongLong
384 QStringLiteral(
"sum" ),
385 QCoreApplication::tr(
"Sum" ),
386 QSet<QVariant::Type>()
389 << QVariant::LongLong
390 << QVariant::ULongLong
395 QStringLiteral(
"mean" ),
396 QCoreApplication::tr(
"Mean" ),
397 QSet<QVariant::Type>()
400 << QVariant::LongLong
401 << QVariant::ULongLong
406 QStringLiteral(
"median" ),
407 QCoreApplication::tr(
"Median" ),
408 QSet<QVariant::Type>()
415 QStringLiteral(
"stdev" ),
416 QCoreApplication::tr(
"Stdev" ),
417 QSet<QVariant::Type>()
420 << QVariant::LongLong
421 << QVariant::ULongLong
426 QStringLiteral(
"stdevsample" ),
427 QCoreApplication::tr(
"Stdev Sample" ),
428 QSet<QVariant::Type>()
431 << QVariant::LongLong
432 << QVariant::ULongLong
437 QStringLiteral(
"range" ),
438 QCoreApplication::tr(
"Range" ),
439 QSet<QVariant::Type>()
441 << QVariant::DateTime
444 << QVariant::LongLong
445 << QVariant::ULongLong
450 QStringLiteral(
"minority" ),
451 QCoreApplication::tr(
"Minority" ),
452 QSet<QVariant::Type>()
455 << QVariant::LongLong
456 << QVariant::ULongLong
462 QStringLiteral(
"majority" ),
463 QCoreApplication::tr(
"Majority" ),
464 QSet<QVariant::Type>()
467 << QVariant::LongLong
468 << QVariant::ULongLong
474 QStringLiteral(
"q1" ),
475 QCoreApplication::tr(
"Q1" ),
476 QSet<QVariant::Type>()
479 << QVariant::LongLong
480 << QVariant::ULongLong
485 QStringLiteral(
"q3" ),
486 QCoreApplication::tr(
"Q3" ),
487 QSet<QVariant::Type>()
490 << QVariant::LongLong
491 << QVariant::ULongLong
496 QStringLiteral(
"iqr" ),
497 QCoreApplication::tr(
"InterQuartileRange" ),
498 QSet<QVariant::Type>()
501 << QVariant::LongLong
502 << QVariant::ULongLong
507 QStringLiteral(
"min_length" ),
508 QCoreApplication::tr(
"Min Length" ),
509 QSet<QVariant::Type>()
514 QStringLiteral(
"max_length" ),
515 QCoreApplication::tr(
"Max Length" ),
516 QSet<QVariant::Type>()
521 QStringLiteral(
"concatenate" ),
522 QCoreApplication::tr(
"Concatenate" ),
523 QSet<QVariant::Type>()
528 QStringLiteral(
"collect" ),
529 QCoreApplication::tr(
"Collect" ),
530 QSet<QVariant::Type>()
534 QStringLiteral(
"array_agg" ),
535 QCoreApplication::tr(
"Array Aggregate" ),
536 QSet<QVariant::Type>()
552 return calculateArrayAggregate( fit, attr, expression, context );
555 switch ( resultType )
559 case QVariant::LongLong:
560 case QVariant::ULongLong:
561 case QVariant::Double:
564 const Qgis::Statistic stat = numericStatFromAggregate( aggregate, &statOk );
568 *error = expression ? QObject::tr(
"Cannot calculate %1 on numeric values" ).arg(
displayName( aggregate ) )
569 : QObject::tr(
"Cannot calculate %1 on numeric fields" ).arg(
displayName( aggregate ) );
575 return calculateNumericAggregate( fit, attr, expression, context, stat );
579 case QVariant::DateTime:
586 *error = ( expression ? QObject::tr(
"Cannot calculate %1 on %2 values" ).arg(
displayName( aggregate ) ) :
587 QObject::tr(
"Cannot calculate %1 on %2 fields" ).arg(
displayName( aggregate ) ) ).arg( resultType == QVariant::Date ? QObject::tr(
"date" ) : QObject::tr(
"datetime" ) );
593 return calculateDateTimeAggregate( fit, attr, expression, context, stat );
596 case QVariant::UserType:
602 return calculateGeometryAggregate( fit, expression, context );
618 return concatenateStrings( fit, attr, expression, context,
delimiter );
625 return concatenateStrings( fit, attr, expression, context,
delimiter,
true );
633 if ( resultType == QVariant::Invalid )
634 typeString = QObject::tr(
"null" );
635 else if ( resultType == QVariant::UserType )
636 typeString = QMetaType::typeName( userType );
638 typeString = resultType == QVariant::String ? QObject::tr(
"string" ) : QVariant::typeToName( resultType );
641 *error = expression ? QObject::tr(
"Cannot calculate %1 on %3 values" ).arg(
displayName( aggregate ), typeString )
642 : QObject::tr(
"Cannot calculate %1 on %3 fields" ).arg(
displayName( aggregate ), typeString );
648 return calculateStringAggregate( fit, attr, expression, context, stat );
816 Q_ASSERT( expression || attr >= 0 );
827 const QVariant v = expression->
evaluate( context );
836 const double val = s.statistic( stat );
837 return std::isnan( val ) ? QVariant() : val;
843 Q_ASSERT( expression || attr >= 0 );
854 const QVariant v = expression->
evaluate( context );
863 return s.statistic( stat );
868 Q_ASSERT( expression );
871 QVector< QgsGeometry > geometries;
876 const QVariant v = expression->
evaluate( context );
877 if ( v.userType() == QMetaType::type(
"QgsGeometry" ) )
889 Q_ASSERT( expression || attr >= 0 );
900 const QVariant v = expression->
evaluate( context );
901 result = v.toString();
908 if ( !unique || !results.contains( result ) )
915QVariant QgsAggregateCalculator::defaultValue(
Qgis::Aggregate aggregate )
const
931 return QVariantList();
958 Q_ASSERT( expression || attr >= 0 );
969 const QVariant v = expression->
evaluate( context );
978 return s.statistic( stat );
984 Q_ASSERT( expression || attr >= 0 );
996 const QVariant v = expression->
evaluate( context );
Statistic
Available generic statistics.
@ StDev
Standard deviation of values.
@ FirstQuartile
First quartile.
@ Median
Median of values.
@ Range
Range of values (max - min)
@ Minority
Minority of values.
@ CountMissing
Number of missing (null) values.
@ Majority
Majority of values.
@ Variety
Variety (count of distinct) values.
@ StDevSample
Sample standard deviation of values.
@ ThirdQuartile
Third quartile.
@ InterQuartileRange
Inter quartile range (IQR)
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ NoFlags
No flags are set.
StringStatistic
Available string statistics.
@ Max
Maximum string value.
@ Min
Minimum string value.
@ MaximumLength
Maximum length of string.
@ Minority
Minority of strings.
@ CountMissing
Number of missing (null) values.
@ Majority
Majority of strings.
@ CountDistinct
Number of distinct string values.
@ MinimumLength
Minimum length of string.
Aggregate
Available aggregates to calculate.
@ StDev
Standard deviation of values (numeric fields only)
@ StringMinimumLength
Minimum length of string (string fields only)
@ FirstQuartile
First quartile (numeric fields only)
@ Mean
Mean of values (numeric fields only)
@ Median
Median of values (numeric fields only)
@ StringMaximumLength
Maximum length of string (string fields only)
@ Range
Range of values (max - min) (numeric and datetime fields only)
@ StringConcatenateUnique
Concatenate unique values with a joining string (string fields only). Specify the delimiter using set...
@ Minority
Minority of values.
@ CountMissing
Number of missing (null) values.
@ ArrayAggregate
Create an array of values.
@ Majority
Majority of values.
@ StDevSample
Sample standard deviation of values (numeric fields only)
@ ThirdQuartile
Third quartile (numeric fields only)
@ CountDistinct
Number of distinct values.
@ StringConcatenate
Concatenate values with a joining string (string fields only). Specify the delimiter using setDelimit...
@ GeometryCollect
Create a multipart geometry from aggregated geometries.
@ InterQuartileRange
Inter quartile range (IQR) (numeric fields only)
DateTimeStatistic
Available date/time statistics.
@ Max
Maximum (latest) datetime value.
@ Min
Minimum (earliest) datetime value.
@ Range
Interval between earliest and latest datetime value.
@ CountMissing
Number of missing (null) values.
@ CountDistinct
Number of distinct datetime values.
const QgsVectorLayer * layer() const
Returns the associated vector layer.
void setParameters(const AggregateParameters ¶meters)
Sets all aggregate parameters from a parameter bundle.
void setFidsFilter(const QgsFeatureIds &fids)
Sets a filter to limit the features used during the aggregate calculation.
static QList< QgsAggregateCalculator::AggregateInfo > aggregates()
Structured information for available aggregates.
QVariant calculate(Qgis::Aggregate aggregate, const QString &fieldOrExpression, QgsExpressionContext *context=nullptr, bool *ok=nullptr, QgsFeedback *feedback=nullptr) const
Calculates the value of an aggregate.
QString delimiter() const
Returns the delimiter used for joining values with the StringConcatenate aggregate.
static QString displayName(Qgis::Aggregate aggregate)
Returns the friendly display name for a aggregate.
static Qgis::Aggregate stringToAggregate(const QString &string, bool *ok=nullptr)
Converts a string to a aggregate type.
QgsAggregateCalculator(const QgsVectorLayer *layer)
Constructor for QgsAggregateCalculator.
Calculator for summary statistics and aggregates for a list of datetimes.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
QgsFeedback * feedback() const
Returns the feedback object that can be queried regularly by the expression to check if evaluation sh...
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
void setFields(const QgsFields &fields)
Convenience function for setting a fields for the context.
static std::tuple< QVariant::Type, int > determineResultType(const QString &expression, const QgsVectorLayer *layer, QgsFeatureRequest request=QgsFeatureRequest(), QgsExpressionContext context=QgsExpressionContext(), bool *foundFeatures=nullptr)
Returns a value type and user type for a given expression.
Class for parsing and evaluation of expressions (formerly called "search strings").
static int expressionToLayerFieldIndex(const QString &expression, const QgsVectorLayer *layer)
Attempts to resolve an expression to a field index from the given layer.
QVariant evaluate()
Evaluate the feature and return the result.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
The OrderByClause class represents an order by clause for a QgsFeatureRequest.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
QgsFeatureRequest & setFilterFids(const QgsFeatureIds &fids)
Sets the feature IDs that should be fetched.
QgsFeatureRequest & setFilterExpression(const QString &expression)
Set the filter expression.
void setFeedback(QgsFeedback *feedback)
Attach a feedback object that can be queried regularly by the iterator to check if it should be cance...
QgsFeatureRequest & setExpressionContext(const QgsExpressionContext &context)
Sets the expression context used to evaluate filter expressions.
QgsFeatureRequest & setOrderBy(const OrderBy &orderBy)
Set a list of order by clauses.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
QgsField at(int i) const
Returns the field at particular index (must be in range 0..N-1).
A geometry is the spatial representation of a feature.
static QgsGeometry collectGeometry(const QVector< QgsGeometry > &geometries)
Creates a new multipart geometry from a list of QgsGeometry objects.
Calculator for summary statistics for a list of doubles.
Calculator for summary statistics and aggregates for a list of strings.
Represents a vector layer which manages a vector based data sets.
QgsFeatureIterator getFeatures(const QgsFeatureRequest &request=QgsFeatureRequest()) const FINAL
Queries the layer for features specified in request.
QgsFields fields() const FINAL
Returns the list of fields of this layer.
QgsExpressionContext createExpressionContext() const FINAL
This method needs to be reimplemented in all classes which implement this interface and return an exp...
QSet< QgsFeatureId > QgsFeatureIds
Structured information about the available aggregates.
A bundle of parameters controlling aggregate calculation.
QString filter
Optional filter for calculating aggregate over a subset of features, or an empty string to use all fe...
QString delimiter
Delimiter to use for joining values with the StringConcatenate aggregate.
QgsFeatureRequest::OrderBy orderBy
Optional order by clauses.