# 38.12.用户定义的聚合
PostgreSQL中的聚合函数是根据国家价值观和状态转移函数。也就是说,聚合使用的状态值在处理每个连续输入行时更新。要定义一个新的聚合函数,可以选择状态值的数据类型、状态的初始值和状态转换函数。状态转换函数获取当前行的前一个状态值和聚合的输入值,并返回一个新的状态值。A.最终功能也可以指定,以防聚合的预期结果与需要保留在运行状态值中的数据不同。最后一个函数获取结束状态值,并返回所需的任何内容作为聚合结果。原则上,转换函数和最终函数只是普通函数,也可以在聚合上下文之外使用。(在实践中,出于性能原因,创建专门的转换函数通常很有帮助,这些函数只有在作为聚合的一部分调用时才能工作。)
因此,除了聚合用户看到的参数和结果数据类型之外,还有一种内部状态值数据类型可能与参数和结果类型都不同。
如果我们定义了一个不使用final函数的聚合,那么我们就有了一个从每一行计算列值的运行函数的聚合。总和
是这种聚合的一个例子。总和
从零开始,始终将当前行的值添加到其运行总数中。例如,如果我们想总和
聚合要处理复数的数据类型,我们只需要该数据类型的加法函数。总体定义如下:
CREATE AGGREGATE sum (complex)
(
sfunc = complex_add,
stype = complex,
initcond = '(0,0)'
);
我们可以这样使用:
SELECT sum(a) FROM test_complex;
sum
### Note
`float8_accum` requires a three-element array, not just two elements, because it accumulates the sum of squares as well as the sum and count of the inputs. This is so that it can be used for some other aggregates as well as `avg`.
Aggregate function calls in SQL allow `DISTINCT` and `ORDER BY` options that control which rows are fed to the aggregate's transition function and in what order. These options are implemented behind the scenes and are not the concern of the aggregate's support functions.
For further details see the [CREATE AGGREGATE](sql-createaggregate.html) command.
### 38.12.1. Moving-Aggregate Mode
[]()[]()
Aggregate functions can optionally support *moving-aggregate mode*, which allows substantially faster execution of aggregate functions within windows with moving frame starting points. (See [Section 3.5](tutorial-window.html) and [Section 4.2.8](sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS) for information about use of aggregate functions as window functions.) The basic idea is that in addition to a normal “forward” transition function, the aggregate provides an *inverse transition function*, which allows rows to be removed from the aggregate's running state value when they exit the window frame. For example a `sum` aggregate, which uses addition as the forward transition function, would use subtraction as the inverse transition function. Without an inverse transition function, the window function mechanism must recalculate the aggregate from scratch each time the frame starting point moves, resulting in run time proportional to the number of input rows times the average frame length. With an inverse transition function, the run time is only proportional to the number of input rows.
The inverse transition function is passed the current state value and the aggregate input value(s) for the earliest row included in the current state. It must reconstruct what the state value would have been if the given input row had never been aggregated, but only the rows following it. This sometimes requires that the forward transition function keep more state than is needed for plain aggregation mode. Therefore, the moving-aggregate mode uses a completely separate implementation from the plain mode: it has its own state data type, its own forward transition function, and its own final function if needed. These can be the same as the plain mode's data type and functions, if there is no need for extra state.
As an example, we could extend the `sum` aggregate given above to support moving-aggregate mode like this:
创建聚合和(复数)(sfunc=complex_add,stype=complex,initcond='(0,0'),msfunc=complex_add,minvfunc=complex_sub,mstype=complex,minitcond='(0,0');
The parameters whose names begin with `m` define the moving-aggregate implementation. Except for the inverse transition function `minvfunc`, they correspond to the plain-aggregate parameters without `m`.
The forward transition function for moving-aggregate mode is not allowed to return null as the new state value. If the inverse transition function returns null, this is taken as an indication that the inverse function cannot reverse the state calculation for this particular input, and so the aggregate calculation will be redone from scratch for the current frame starting position. This convention allows moving-aggregate mode to be used in situations where there are some infrequent cases that are impractical to reverse out of the running state value. The inverse transition function can “punt” on these cases, and yet still come out ahead so long as it can work for most cases. As an example, an aggregate working with floating-point numbers might choose to punt when a `NaN` (not a number) input has to be removed from the running state value.
When writing moving-aggregate support functions, it is important to be sure that the inverse transition function can reconstruct the correct state value exactly. Otherwise there might be user-visible differences in results depending on whether the moving-aggregate mode is used. An example of an aggregate for which adding an inverse transition function seems easy at first, yet where this requirement cannot be met is `sum` over `float4` or `float8` inputs. A naive declaration of `sum(`float8`)` could be
创建聚合不安全总和(float8)(stype=float8,sfunc=float8pl,mstype=float8,msfunc=float8pl,minvfunc=float8mi);
This aggregate, however, can give wildly different results than it would have without the inverse transition function. For example, consider
从(值(1,1.0e20::float8)、(2,1.0::float8))中选择(按当前行和下面1行之间的n行排序)作为v(n,x);
This query returns `0` as its second result, rather than the expected answer of `1`. The cause is the limited precision of floating-point values: adding `1` to `1e20` results in `1e20` again, and so subtracting `1e20` from that yields `0`, not `1`. Note that this is a limitation of floating-point arithmetic in general, not a limitation of PostgreSQL.
### 38.12.2. Polymorphic and Variadic Aggregates
[]()[]()
Aggregate functions can use polymorphic state transition functions or final functions, so that the same functions can be used to implement multiple aggregates. See [Section 38.2.5](extend-type-system.html#EXTEND-TYPES-POLYMORPHIC) for an explanation of polymorphic functions. Going a step further, the aggregate function itself can be specified with polymorphic input type(s) and state type, allowing a single aggregate definition to serve for multiple input data types. Here is an example of a polymorphic aggregate:
创建聚合数组_accum(anycompatible)(sfunc=array_append,stype=anycompatiblearray,initcond='{}');
Here, the actual state type for any given aggregate call is the array type having the actual input type as elements. The behavior of the aggregate is to concatenate all the inputs into an array of that type. (Note: the built-in aggregate `array_agg` provides similar functionality, with better performance than this definition would have.)
Here's the output using two different actual data types as arguments:
从pg_属性中选择attrelid::regclass,array_accum(attname),其中attnum>0,attrelid='pg_tablespace'::regclass按attrelid分组;
attrelid |数组_accum
# 笔记
变量聚合很容易在与订购人
选项(参见第4.2.7节),因为解析器无法判断在这种组合中是否给出了错误数量的实际参数。记住,一切都是正确的订购人
是排序键,而不是聚合的参数。例如,在
SELECT myaggregate(a ORDER BY a, b, c) FROM ...
解析器将其视为一个聚合函数参数和三个排序键。然而,用户可能是有意的
SELECT myaggregate(a, b, c ORDER BY a) FROM ...
如果myaggregate
是可变的,这两个调用可能完全有效。
出于同样的原因,在创建具有相同名称和不同数量的正则参数的聚合函数之前,最好三思而后行。
# 38.12.3.有序集聚集体
到目前为止,我们描述的聚合是“正常”聚合。PostgreSQL还支持有序集聚集体,在两个关键方面不同于普通骨料。首先,除了每个输入行计算一次的普通聚合参数外,有序集聚合还可以有“直接”参数,每个聚合操作只计算一次。其次,普通聚合参数的语法明确指定了它们的排序顺序。有序集合聚合通常用于实现依赖于特定行顺序(例如秩或百分位数)的计算,因此排序顺序是任何调用的一个必要方面。例如,内置的百分位盘
相当于:
CREATE FUNCTION ordered_set_transition(internal, anyelement)
RETURNS internal ...;
CREATE FUNCTION percentile_disc_final(internal, float8, anyelement)
RETURNS anyelement ...;
CREATE AGGREGATE percentile_disc (float8 ORDER BY anyelement)
(
sfunc = ordered_set_transition,
stype = internal,
finalfunc = percentile_disc_final,
finalfunc_extra
);
这个聚合需要一段时间浮动8
直接参数(百分比分数)和聚合输入,可以是任何可排序的数据类型。它可以用来获得这样的家庭收入中值:
SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY income) FROM households;
percentile_disc
### 38.12.4. Partial Aggregation
[]()
Optionally, an aggregate function can support *partial aggregation*. The idea of partial aggregation is to run the aggregate's state transition function over different subsets of the input data independently, and then to combine the state values resulting from those subsets to produce the same state value that would have resulted from scanning all the input in a single operation. This mode can be used for parallel aggregation by having different worker processes scan different portions of a table. Each worker produces a partial state value, and at the end those state values are combined to produce a final state value. (In the future this mode might also be used for purposes such as combining aggregations over local and remote tables; but that is not implemented yet.)
To support partial aggregation, the aggregate definition must provide a *combine function*, which takes two values of the aggregate's state type (representing the results of aggregating over two subsets of the input rows) and produces a new value of the state type, representing what the state would have been after aggregating over the combination of those sets of rows. It is unspecified what the relative order of the input rows from the two sets would have been. This means that it's usually impossible to define a useful combine function for aggregates that are sensitive to input row order.
As simple examples, `MAX` and `MIN` aggregates can be made to support partial aggregation by specifying the combine function as the same greater-of-two or lesser-of-two comparison function that is used as their transition function. `SUM` aggregates just need an addition function as combine function. (Again, this is the same as their transition function, unless the state value is wider than the input data type.)
The combine function is treated much like a transition function that happens to take a value of the state type, not of the underlying input type, as its second argument. In particular, the rules for dealing with null values and strict functions are similar. Also, if the aggregate definition specifies a non-null `initcond`, keep in mind that that will be used not only as the initial state for each partial aggregation run, but also as the initial state for the combine function, which will be called to combine each partial result into that state.
If the aggregate's state type is declared as `internal`, it is the combine function's responsibility that its result is allocated in the correct memory context for aggregate state values. This means in particular that when the first input is `NULL` it's invalid to simply return the second input, as that value will be in the wrong context and will not have sufficient lifespan.
When the aggregate's state type is declared as `internal`, it is usually also appropriate for the aggregate definition to provide a *serialization function* and a *deserialization function*, which allow such a state value to be copied from one process to another. Without these functions, parallel aggregation cannot be performed, and future applications such as local/remote aggregation will probably not work either.
A serialization function must take a single argument of type `internal` and return a result of type `bytea`, which represents the state value packaged up into a flat blob of bytes. Conversely, a deserialization function reverses that conversion. It must take two arguments of types `bytea` and `internal`, and return a result of type `internal`. (The second argument is unused and is always zero, but it is required for type-safety reasons.) The result of the deserialization function should simply be allocated in the current memory context, as unlike the combine function's result, it is not long-lived.
Worth noting also is that for an aggregate to be executed in parallel, the aggregate itself must be marked `PARALLEL SAFE`. The parallel-safety markings on its support functions are not consulted.
### 38.12.5. Support Functions for Aggregates
[]()
A function written in C can detect that it is being called as an aggregate support function by calling `AggCheckCallContext`, for example:
if(AggCheckCallContext(fcinfo,NULL))
One reason for checking this is that when it is true, the first input must be a temporary state value and can therefore safely be modified in-place rather than allocating a new copy. See `int8inc()` for an example. (While aggregate transition functions are always allowed to modify the transition value in-place, aggregate final functions are generally discouraged from doing so; if they do so, the behavior must be declared when creating the aggregate. See [CREATE AGGREGATE](sql-createaggregate.html) for more detail.)
The second argument of `AggCheckCallContext` can be used to retrieve the memory context in which aggregate state values are being kept. This is useful for transition functions that wish to use “expanded” objects (see [Section 38.13.1](xtypes.html#XTYPES-TOAST)) as their state values. On first call, the transition function should return an expanded object whose memory context is a child of the aggregate state context, and then keep returning the same expanded object on subsequent calls. See `array_append()` for an example. (`array_append()` is not the transition function of any built-in aggregate, but it is written to behave efficiently when used as transition function of a custom aggregate.)
Another support routine available to aggregate functions written in C is `AggGetAggref`, which returns the `Aggref` parse node that defines the aggregate call. This is mainly useful for ordered-set aggregates, which can inspect the substructure of the `Aggref` node to find out what sort ordering they are supposed to implement. Examples can be found in `orderedsetaggs.c` in the PostgreSQL source code.