zoukankan      html  css  js  c++  java
  • 12.20.1汇总功能说明

    12.20.1 Aggregate Function Descriptions

    This section describes aggregate functions that operate on sets of values. They are often used with a GROUP BY clause to group values into subsets.

    Table 12.25 Aggregate Functions

    NameDescription
    AVG() Return the average value of the argument
    BIT_AND() Return bitwise AND
    BIT_OR() Return bitwise OR
    BIT_XOR() Return bitwise XOR
    COUNT() Return a count of the number of rows returned
    COUNT(DISTINCT) Return the count of a number of different values
    GROUP_CONCAT() Return a concatenated string
    JSON_ARRAYAGG() Return result set as a single JSON array
    JSON_OBJECTAGG() Return result set as a single JSON object
    MAX() Return the maximum value
    MIN() Return the minimum value
    STD() Return the population standard deviation
    STDDEV() Return the population standard deviation
    STDDEV_POP() Return the population standard deviation
    STDDEV_SAMP() Return the sample standard deviation
    SUM() Return the sum
    VAR_POP() Return the population standard variance
    VAR_SAMP() Return the sample variance
    VARIANCE() Return the population standard variance
     

    Unless otherwise stated, aggregate functions ignore NULL values.

    If you use an aggregate function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows. For more information, see Section 12.20.3, “MySQL Handling of GROUP BY”.

    Most aggregate functions can be used as window functions. Those that can be used this way are signified in their syntax description by [over_clause], representing an optional OVER clause. over_clause is described in Section 12.21.2, “Window Function Concepts and Syntax”, which also includes other information about window function usage.

    For numeric arguments, the variance and standard deviation functions return a DOUBLE value. The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).

    The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the values to numbers, losing everything after the first nonnumeric character.) To work around this problem, convert to numeric units, perform the aggregate operation, and convert back to a temporal value. Examples:

    SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name;
    SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_name;

    Functions such as SUM() or AVG() that expect a numeric argument cast the argument to a number if necessary. For SET or ENUM values, the cast operation causes the underlying numeric value to be used.

    The BIT_AND()BIT_OR(), and BIT_XOR() aggregate functions perform bit operations. Prior to MySQL 8.0, bit functions and operators required BIGINT (64-bit integer) arguments and returned BIGINT values, so they had a maximum range of 64 bits. Non-BIGINT arguments were converted to BIGINT prior to performing the operation and truncation could occur.

    In MySQL 8.0, bit functions and operators permit binary string type arguments (BINARYVARBINARY, and the BLOB types) and return a value of like type, which enables them to take arguments and produce return values larger than 64 bits. For discussion about argument evaluation and result types for bit operations, see the introductory discussion in Section 12.13, “Bit Functions and Operators”.

    • AVG([DISTINCT] expr) [over_clause]

      Returns the average value of expr. The DISTINCT option can be used to return the average of the distinct values of expr.

      If there are no matching rows, AVG() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

      mysql> SELECT student_name, AVG(test_score)
             FROM student
             GROUP BY student_name;
    • BIT_AND(expr) [over_clause]

      Returns the bitwise AND of all bits in expr.

      The result type depends on whether the function argument values are evaluated as binary strings or numbers:

      • Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or NULL literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.

      • Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error occurs. Numeric evaluation produces an unsigned 64-bit integer.

      If there are no matching rows, BIT_AND() returns a neutral value (all bits set to 1) having the same length as the argument values.

      NULL values do not affect the result unless all values are NULL. In that case, the result is a neutral value having the same length as the argument values.

      For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.13, “Bit Functions and Operators”.

      As of MySQL 8.0.12, this function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • BIT_OR(expr) [over_clause]

      Returns the bitwise OR of all bits in expr.

      The result type depends on whether the function argument values are evaluated as binary strings or numbers:

      • Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or NULL literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.

      • Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error occurs. Numeric evaluation produces an unsigned 64-bit integer.

      If there are no matching rows, BIT_OR() returns a neutral value (all bits set to 0) having the same length as the argument values.

      NULL values do not affect the result unless all values are NULL. In that case, the result is a neutral value having the same length as the argument values.

      For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.13, “Bit Functions and Operators”.

      As of MySQL 8.0.12, this function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • BIT_XOR(expr) [over_clause]

      Returns the bitwise XOR of all bits in expr.

      The result type depends on whether the function argument values are evaluated as binary strings or numbers:

      • Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or NULL literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.

      • Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an ER_INVALID_BITWISE_OPERANDS_SIZE error occurs. If the argument size exceeds 511 bytes, an ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE error occurs. Numeric evaluation produces an unsigned 64-bit integer.

      If there are no matching rows, BIT_XOR() returns a neutral value (all bits set to 0) having the same length as the argument values.

      NULL values do not affect the result unless all values are NULL. In that case, the result is a neutral value having the same length as the argument values.

      For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.13, “Bit Functions and Operators”.

      As of MySQL 8.0.12, this function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • COUNT(expr) [over_clause]

      Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.

      If there are no matching rows, COUNT() returns 0.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

      mysql> SELECT student.student_name,COUNT(*)
             FROM student,course
             WHERE student.student_id=course.student_id
             GROUP BY student_name;

      COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.

      For transactional storage engines such as InnoDB, storing an exact row count is problematic. Multiple transactions may be occurring at the same time, each of which may affect the count.

      InnoDB does not keep an internal count of rows in a table because concurrent transactions might see” different numbers of rows at the same time. Consequently, SELECT COUNT(*) statements only count rows visible to the current transaction.

      As of MySQL 8.0.13, SELECT COUNT(*) FROM tbl_name query performance for InnoDB tables is optimized for single-threaded workloads if there are no extra clauses such as WHERE or GROUP BY.

      InnoDB processes SELECT COUNT(*) statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. If a secondary index is not present, InnoDB processes SELECT COUNT(*) statements by scanning the clustered index.

      Processing SELECT COUNT(*) statements takes some time if index records are not entirely in the buffer pool. For a faster count, create a counter table and let your application update it according to the inserts and deletes it does. However, this method may not scale well in situations where thousands of concurrent transactions are initiating updates to the same counter table. If an approximate row count is sufficient, use SHOW TABLE STATUS.

      InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference.

      For MyISAM tables, COUNT(*) is optimized to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause. For example:

      mysql> SELECT COUNT(*) FROM student;

      This optimization only applies to MyISAM tables, because an exact row count is stored for this storage engine and can be accessed very quickly. COUNT(1) is only subject to the same optimization if the first column is defined as NOT NULL.

    • COUNT(DISTINCT expr,[expr...])

      Returns a count of the number of rows with different non-NULLexpr values.

      If there are no matching rows, COUNT(DISTINCT) returns 0.

      mysql> SELECT COUNT(DISTINCT results) FROM student;

      In MySQL, you can obtain the number of distinct expression combinations that do not contain NULL by giving a list of expressions. In standard SQL, you would have to do a concatenation of all expressions inside COUNT(DISTINCT ...).

    • GROUP_CONCAT(expr)

      This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows:

      GROUP_CONCAT([DISTINCT] expr [,expr ...]
                   [ORDER BY {unsigned_integer | col_name | expr}
                       [ASC | DESC] [,col_name ...]]
                   [SEPARATOR str_val])
      mysql> SELECT student_name,
               GROUP_CONCAT(test_score)
             FROM student
             GROUP BY student_name;

      Or:

      mysql> SELECT student_name,
               GROUP_CONCAT(DISTINCT test_score
                            ORDER BY test_score DESC SEPARATOR ' ')
             FROM student
             GROUP BY student_name;

      In MySQL, you can get the concatenated values of expression combinations. To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (,). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.

      The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:

      SET [GLOBAL | SESSION] group_concat_max_len = val;

      The return value is a nonbinary or binary string, depending on whether the arguments are nonbinary or binary strings. The result type is TEXT or BLOB unless group_concat_max_len is less than or equal to 512, in which case the result type is VARCHAR or VARBINARY.

      See also CONCAT() and CONCAT_WS()Section 12.8, “String Functions and Operators”.

    • JSON_ARRAYAGG(col_or_expr) [over_clause]

      Aggregates a result set as a single JSON array whose elements consist of the rows. The order of elements in this array is undefined. The function acts on a column or an expression that evaluates to a single value. Returns NULL if the result contains no rows, or in the event of an error.

      As of MySQL 8.0.14, this function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

      mysql> SELECT o_id, attribute, value FROM t3;
      +------+-----------+-------+
      | o_id | attribute | value |
      +------+-----------+-------+
      |    2 | color     | red   |
      |    2 | fabric    | silk  |
      |    3 | color     | green |
      |    3 | shape     | square|
      +------+-----------+-------+
      4 rows in set (0.00 sec)
      
      mysql> SELECT o_id, JSON_ARRAYAGG(attribute) AS attributes
           > FROM t3 GROUP BY o_id;
      +------+---------------------+
      | o_id | attributes          |
      +------+---------------------+
      |    2 | ["color", "fabric"] |
      |    3 | ["color", "shape"]  |
      +------+---------------------+
      2 rows in set (0.00 sec)
    • JSON_OBJECTAGG(keyvalue) [over_clause]

      Takes two column names or expressions as arguments, the first of these being used as a key and the second as a value, and returns a JSON object containing key-value pairs. Returns NULL if the result contains no rows, or in the event of an error. An error occurs if any key name is NULL or the number of arguments is not equal to 2.

      As of MySQL 8.0.14, this function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

      mysql> SELECT o_id, attribute, value FROM t3;
      +------+-----------+-------+
      | o_id | attribute | value |
      +------+-----------+-------+
      |    2 | color     | red   |
      |    2 | fabric    | silk  |
      |    3 | color     | green |
      |    3 | shape     | square|
      +------+-----------+-------+
      4 rows in set (0.00 sec)
      
      mysql> SELECT o_id, JSON_OBJECTAGG(attribute, value)
           > FROM t3 GROUP BY o_id;
      +------+---------------------------------------+
      | o_id | JSON_OBJECTAGG(attribute, value)      |
      +------+---------------------------------------+
      |    2 | {"color": "red", "fabric": "silk"}    |
      |    3 | {"color": "green", "shape": "square"} |
      +------+---------------------------------------+
      2 rows in set (0.00 sec)

      Duplicate key handling.  When the result of this function is normalized, values having duplicate keys are discarded. In keeping with the MySQL JSON data type specification that does not permit duplicate keys, only the last value encountered is used with that key in the returned object (last duplicate key wins”). This means that the result of using this function on columns from a SELECT can depend on the order in which the rows are returned, which is not guaranteed.

      When used as a window function, if there are duplicate keys within a frame, only the last value for the key is present in the result. The value for the key from the last row in the frame is deterministic if the ORDER BY specification guarantees that the values have a specific order. If not, the resulting value of the key is nondeterministic.

      Consider the following:

      mysql> CREATE TABLE t(c VARCHAR(10), i INT);
      Query OK, 0 rows affected (0.33 sec)
      
      mysql> INSERT INTO t VALUES ('key', 3), ('key', 4), ('key', 5);
      Query OK, 3 rows affected (0.10 sec)
      Records: 3  Duplicates: 0  Warnings: 0
      
      mysql> SELECT c, i FROM t;
      +------+------+
      | c    | i    |
      +------+------+
      | key  |    3 |
      | key  |    4 |
      | key  |    5 |
      +------+------+
      3 rows in set (0.00 sec)
      
      mysql> SELECT JSON_OBJECTAGG(c, i) FROM t;
      +----------------------+
      | JSON_OBJECTAGG(c, i) |
      +----------------------+
      | {"key": 5}           |
      +----------------------+
      1 row in set (0.00 sec)
      
      mysql> DELETE FROM t;
      Query OK, 3 rows affected (0.08 sec)
      
      mysql> INSERT INTO t VALUES ('key', 3), ('key', 5), ('key', 4);
      Query OK, 3 rows affected (0.06 sec)
      Records: 3  Duplicates: 0  Warnings: 0
      
      mysql> SELECT c, i FROM t;
      +------+------+
      | c    | i    |
      +------+------+
      | key  |    3 |
      | key  |    5 |
      | key  |    4 |
      +------+------+
      3 rows in set (0.00 sec)
      
      mysql> SELECT JSON_OBJECTAGG(c, i) FROM t;
      +----------------------+
      | JSON_OBJECTAGG(c, i) |
      +----------------------+
      | {"key": 4}           |
      +----------------------+
      1 row in set (0.00 sec)

      The key chosen from the last query is nondeterministic. If you prefer a particular key ordering, you can invoke JSON_OBJECTAGG() as a window function by including an OVER clause with an ORDER BY specification to impose a particular order on frame rows. The following examples show what happens with and without ORDER BY for a few different frame specifications.

      Without ORDER BY, the frame is the entire partition:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER () AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 4}  |
      | {"key": 4}  |
      | {"key": 4}  |
      +-------------+

      With ORDER BY, where the frame is the default of RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW (in both ascending and descending order):

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i) AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 3}  |
      | {"key": 4}  |
      | {"key": 5}  |
      +-------------+
      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i DESC) AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      | {"key": 4}  |
      | {"key": 3}  |
      +-------------+

      With ORDER BY and an explicit frame of the entire partition:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i
                  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
              AS json_object
             FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      | {"key": 5}  |
      | {"key": 5}  |
      +-------------+

      To return a particular key value (such as the smallest or largest), include a LIMIT clause in the appropriate query. For example:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i) AS json_object FROM t LIMIT 1;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 3}  |
      +-------------+
      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i DESC) AS json_object FROM t LIMIT 1;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      +-------------+

      See Normalization, Merging, and Autowrapping of JSON Values, for additional information and examples.

    • MAX([DISTINCT] expr) [over_clause]

      Returns the maximum value of exprMAX() may take a string argument; in such cases, it returns the maximum string value. See Section 8.3.1, “How MySQL Uses Indexes”. The DISTINCT keyword can be used to find the maximum of the distinct values of expr, however, this produces the same result as omitting DISTINCT.

      If there are no matching rows, MAX() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

      mysql> SELECT student_name, MIN(test_score), MAX(test_score)
             FROM student
             GROUP BY student_name;

      For MAX(), MySQL currently compares ENUM and SET columns by their string value rather than by the string's relative position in the set. This differs from how ORDER BY compares them.

    • MIN([DISTINCT] expr) [over_clause]

      Returns the minimum value of exprMIN() may take a string argument; in such cases, it returns the minimum string value. See Section 8.3.1, “How MySQL Uses Indexes”. The DISTINCT keyword can be used to find the minimum of the distinct values of expr, however, this produces the same result as omitting DISTINCT.

      If there are no matching rows, MIN() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

      mysql> SELECT student_name, MIN(test_score), MAX(test_score)
             FROM student
             GROUP BY student_name;

      For MIN(), MySQL currently compares ENUM and SET columns by their string value rather than by the string's relative position in the set. This differs from how ORDER BY compares them.

    • STD(expr) [over_clause]

      Returns the population standard deviation of exprSTD() is a synonym for the standard SQL function STDDEV_POP(), provided as a MySQL extension.

      If there are no matching rows, STD() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • STDDEV(expr) [over_clause]

      Returns the population standard deviation of exprSTDDEV() is a synonym for the standard SQL function STDDEV_POP(), provided for compatibility with Oracle.

      If there are no matching rows, STDDEV() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • STDDEV_POP(expr) [over_clause]

      Returns the population standard deviation of expr (the square root of VAR_POP()). You can also use STD() or STDDEV(), which are equivalent but not standard SQL.

      If there are no matching rows, STDDEV_POP() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • STDDEV_SAMP(expr) [over_clause]

      Returns the sample standard deviation of expr (the square root of VAR_SAMP().

      If there are no matching rows, STDDEV_SAMP() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • SUM([DISTINCT] expr) [over_clause]

      Returns the sum of expr. If the return set has no rows, SUM() returns NULL. The DISTINCT keyword can be used to sum only the distinct values of expr.

      If there are no matching rows, SUM() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used with DISTINCT.

    • VAR_POP(expr) [over_clause]

      Returns the population standard variance of expr. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. You can also use VARIANCE(), which is equivalent but is not standard SQL.

      If there are no matching rows, VAR_POP() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • VAR_SAMP(expr) [over_clause]

      Returns the sample variance of expr. That is, the denominator is the number of rows minus one.

      If there are no matching rows, VAR_SAMP() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    • VARIANCE(expr) [over_clause]

      Returns the population standard variance of exprVARIANCE() is a synonym for the standard SQL function VAR_POP(), provided as a MySQL extension.

      If there are no matching rows, VARIANCE() returns NULL.

      This function executes as a window function if over_clause is present. over_clause is as described in Section 12.21.2, “Window Function Concepts and Syntax”.

    12.20.1汇总功能说明

    本节介绍对值集进行操作的聚合函数。它们通常与GROUP BY子句一起使用,以将值分组为子集。

    表12.25汇总函数

    姓名描述
    AVG() 返回参数的平均值
    BIT_AND() 按位返回AND
    BIT_OR() 按位返回OR
    BIT_XOR() 返回按位异或
    COUNT() 返回计数返回的行数
    COUNT(DISTINCT) 返回多个不同值的计数
    GROUP_CONCAT() 返回串联的字符串
    JSON_ARRAYAGG() 将结果集作为单个JSON数组返回
    JSON_OBJECTAGG() 将结果集作为单个JSON对象返回
    MAX() 返回最大值
    MIN() 返回最小值
    STD() 返回人口标准差
    STDDEV() 返回人口标准差
    STDDEV_POP() 返回人口标准差
    STDDEV_SAMP() 返回样品标准偏差
    SUM() 返回总和
    VAR_POP() 返回总体标准方差
    VAR_SAMP() 返回样本方差
    VARIANCE() 返回总体标准方差
     

    除非另有说明,否则聚合函数将忽略 NULL值。

    如果在不包含任何GROUP BY子句的语句中使用聚合函数 ,则等效于对所有行进行分组。有关更多信息,请参见 第12.20.3节“ GROUP BY的MySQL处理”

    大多数聚合函数都可以用作窗口函数。可以以这种方式使用的语法在其语法描述中由 表示,表示可选子句。 第12.21.2节“窗口函数的概念和语法”中对此进行了描述,该 文档还包括有关窗口函数用法的其他信息。 [over_clause]OVERover_clause

    对于数字参数,方差和标准偏差函数返回一个DOUBLE值。SUM()和 AVG()函数返回一个 DECIMAL为准确值参数(整数或值DECIMAL),以及DOUBLE为近似值参数(值FLOAT或 DOUBLE)。

    SUM()和 AVG()聚合函数不具有时间价值的工作。(它们将值转换为数字,第一个非数字字符后会丢失所有内容。)要解决此问题,请转换为数字单位,执行合计运算,然后转换回时间值。例子:

    SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name;
    SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_name;

    诸如SUM()或 AVG()期望数字参数的函数在必要时将参数强制转换为数字。对于 SET或 ENUM值,强制转换操作将导致使用基础数字值。

    BIT_AND(), BIT_OR()和 BIT_XOR()聚合函数执行位操作。在MySQL 8.0之前,位函数和运算符需要参数BIGINT(64位整数)和返回 BIGINT值,因此它们的最大范围为64位。在执行该操作之前,将BIGINT参数转换为BIGINT,并且可能会发生截断。

    在MySQL 8.0中,位函数和运算符允许使用二进制字符串类型的参数(BINARY, VARBINARY和 BLOB类型),并返回类似类型的值,这使它们能够接受参数并产生大于64位的返回值。有关位运算的参数求值和结果类型的讨论,请参见第12.13节“位函数和运算符”中的介绍性讨论

    • AVG([DISTINCT] expr) [over_clause]

      返回的平均值 expr该 DISTINCT选项可用于返回的不同值的平均值 expr

      如果没有匹配的行,则 AVG()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述不能与一起使用DISTINCT

      mysql> SELECT student_name, AVG(test_score)
             FROM student
             GROUP BY student_name;
    • BIT_AND(expr) [over_clause]

      返回AND中所有位 的按位排序expr

      结果类型取决于函数参数值是二进制字符串还是数字:

      • 当参数值具有二进制字符串类型且参数不是十六进制文字,位文字或NULL文字时,将进行二进制字符串求值 否则会进行数值求值,并根据需要将参数值转换为无符号的64位整数。

      • 二进制字符串求值将生成与参数值长度相同的二进制字符串。如果参数值的长度不相等, ER_INVALID_BITWISE_OPERANDS_SIZE 则会发生错误。如果参数大小超过511个字节, ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE 则会发生错误。数值评估产生一个无符号的64位整数。

      如果没有匹配的行,则 BIT_AND()返回长度与参数值相同的中性值(所有位均设置为1)。

      NULL除非所有值均为,否则这些值不会影响结果NULL在那种情况下,结果是一个中性值,其长度与自变量值相同。

      有关参数评估和结果类型的更多信息,请参见第12.13节“位函数和运算符”中的介绍性讨论 

      从MySQL 8.0.12开始,此函数作为窗口函数(如果over_clause存在)执行。over_clause第12.21.2节“窗口函数的概念和语法”中所述

    • BIT_OR(expr) [over_clause]

      返回OR中所有位 的按位排序expr

      结果类型取决于函数参数值是二进制字符串还是数字:

      • 当参数值具有二进制字符串类型且参数不是十六进制文字,位文字或NULL文字时,将进行二进制字符串求值 否则会进行数值求值,并根据需要将参数值转换为无符号的64位整数。

      • 二进制字符串求值将生成与参数值长度相同的二进制字符串。如果参数值的长度不相等, ER_INVALID_BITWISE_OPERANDS_SIZE 则会发生错误。如果参数大小超过511个字节, ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE 则会发生错误。数值评估产生一个无符号的64位整数。

      如果没有匹配的行,则 BIT_OR()返回长度与参数值相同的中性值(所有位均设置为0)。

      NULL除非所有值均为,否则这些值不会影响结果NULL在那种情况下,结果是一个中性值,其长度与自变量值相同。

      有关参数评估和结果类型的更多信息,请参见第12.13节“位函数和运算符”中的介绍性讨论 

      从MySQL 8.0.12开始,此函数作为窗口函数(如果over_clause存在)执行。over_clause第12.21.2节“窗口函数的概念和语法”中所述

    • BIT_XOR(expr) [over_clause]

      返回XOR中所有位的按位排序expr

      结果类型取决于函数参数值是二进制字符串还是数字:

      • 当参数值具有二进制字符串类型且参数不是十六进制文字,位文字或NULL文字时,将进行二进制字符串求值 否则会进行数值求值,并根据需要将参数值转换为无符号的64位整数。

      • 二进制字符串求值将生成与参数值长度相同的二进制字符串。如果参数值的长度不相等, ER_INVALID_BITWISE_OPERANDS_SIZE 则会发生错误。如果参数大小超过511个字节, ER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE 则会发生错误。数值评估产生一个无符号的64位整数。

      如果没有匹配的行,则 BIT_XOR()返回长度与参数值相同的中性值(所有位均设置为0)。

      NULL除非所有值均为,否则这些值不会影响结果NULL在那种情况下,结果是一个中性值,其长度与自变量值相同。

      有关参数评估和结果类型的更多信息,请参见第12.13节“位函数和运算符”中的介绍性讨论 

      从MySQL 8.0.12开始,此函数作为窗口函数(如果over_clause存在)执行。over_clause第12.21.2节“窗口函数的概念和语法”中所述

    • COUNT(expr) [over_clause]

      返回 语句检索的行中非NULL 值的数量的计数结果是一个 值。 exprSELECTBIGINT

      如果没有匹配的行,则 COUNT()返回 0

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

      mysql> SELECT student.student_name,COUNT(*)
             FROM student,course
             WHERE student.student_id=course.student_id
             GROUP BY student_name;

      COUNT(*)有所不同,因为它返回获取的行数的计数,无论它们是否包含 NULL值。

      对于诸如之类的事务性存储引擎 InnoDB,存储准确的行数是有问题的。可能同时发生多个事务,每个事务都可能影响计数。

      InnoDB不会在表中保留内部行数,因为并发事务可能同时 看到不同数量的行。因此,SELECT COUNT(*) 语句仅对当前事务可见的行进行计数。

      从MySQL 8.0.13开始,如果没有诸如或的 额外子句,则针对单线程工作负载优化表的查询性能。 SELECT COUNT(*) FROM tbl_nameInnoDBWHEREGROUP BY

      InnoDBSELECT COUNT(*)除非索引或优化器提示指示优化器使用其他索引,否则通过遍历最小的可用二级索引来处理语句。如果不存在二级索引,则通过扫描聚集索引来InnoDB 处理SELECT COUNT(*)语句。

      SELECT COUNT(*)如果索引记录不完​​全在缓冲池中,则 处理语句将花费一些时间。为了获得更快的计数,请创建一个计数器表,并让您的应用程序根据其插入和删除操作对其进行更新。但是,在成千上万的并发事务正在启动对同一计数器表的更新的情况下,此方法可能无法很好地扩展。如果近似的行数足够,请使用 SHOW TABLE STATUS

      InnoDB 以相同的方式处理SELECT COUNT(*)SELECT COUNT(1)操作。没有性能差异。

      对于MyISAM表,COUNT(*)如果SELECT从一个表中进行检索,没有其他列被检索,并且没有 WHERE子句, 则优化后可以非常快速地返回 例如:

      mysql> SELECT COUNT(*) FROM student;

      此优化仅适用于MyISAM 表,因为为该存储引擎存储了准确的行数,并且可以非常快速地对其进行访问。 COUNT(1)如果第一列定义为,则仅进行相同的优化NOT NULL

    • COUNT(DISTINCT expr,[expr...])

      返回具有不同非NULL expr 值的行数的计数

      如果没有匹配的行,则 COUNT(DISTINCT)返回 0

      mysql> SELECT COUNT(DISTINCT results) FROM student;

      在MySQL中,可以NULL通过提供表达式列表来获得不包含的不同表达式组合的数量在标准SQL中,您必须对中的所有表达式进行串联 COUNT(DISTINCT ...)

    • GROUP_CONCAT(expr)

      此函数返回一个字符串结果,其中NULL包含来自组的串联非值。NULL如果没有非NULL,则返回 完整语法如下:

      GROUP_CONCAT([DISTINCT] expr [,expr ...]
                   [ORDER BY {unsigned_integer | col_name | expr}
                       [ASC | DESC] [,col_name ...]]
                   [SEPARATOR str_val])
      mysql> SELECT student_name,
               GROUP_CONCAT(test_score)
             FROM student
             GROUP BY student_name;

      或者:

      mysql> SELECT student_name,
               GROUP_CONCAT(DISTINCT test_score
                            ORDER BY test_score DESC SEPARATOR ' ')
             FROM student
             GROUP BY student_name;

      在MySQL中,您可以获取表达式组合的串联值。要消除重复值,请使用该 DISTINCT子句。要对结果中的值进行排序,请使用ORDER BY子句。要以相反的顺序DESC 排序,请在ORDER BY子句中将(降序)关键字添加到要作为排序依据的列的名称默认为升序;这可以使用ASC关键字明确指定组中值之间的默认分隔符是逗号(,)。要明确指定分隔符,请使用SEPARATOR后跟应该在组值之间插入的字符串文字值。要完全消除分隔符,请指定 SEPARATOR ''

      结果将被截断为group_concat_max_len 系统变量给定的最大长度,该默认值的默认值为1024。尽管返回值的有效最大长度受的限制,但可以将值设置得更高 max_allowed_packetgroup_concat_max_len在运行时更改value的语法 如下,其中val 是一个无符号整数:

      SET [GLOBAL | SESSION] group_concat_max_len = val;

      返回值是非二进制或二进制字符串,具体取决于参数是非二进制还是二进制字符串。结果类型为TEXT或, BLOB除非 group_concat_max_len小于或等于512,在这种情况下,结果类型为 VARCHAR或 VARBINARY

      另请参见CONCAT()和 CONCAT_WS(): 第12.8节“字符串函数和运算符”

    • JSON_ARRAYAGG(col_or_expr) [over_clause]

      将结果集聚合为单个 JSON数组,其元素由行组成。此数组中元素的顺序是不确定的。该函数作用于计算为单个值的列或表达式。返回 NULL如果结果不包含任何行,或在错误的事件。

      从MySQL 8.0.14开始,此函数作为窗口函数(如果over_clause存在)执行。over_clause第12.21.2节“窗口函数的概念和语法”中所述

      mysql> SELECT o_id, attribute, value FROM t3;
      +------+-----------+-------+
      | o_id | attribute | value |
      +------+-----------+-------+
      |    2 | color     | red   |
      |    2 | fabric    | silk  |
      |    3 | color     | green |
      |    3 | shape     | square|
      +------+-----------+-------+
      4 rows in set (0.00 sec)
      
      mysql> SELECT o_id, JSON_ARRAYAGG(attribute) AS attributes
           > FROM t3 GROUP BY o_id;
      +------+---------------------+
      | o_id | attributes          |
      +------+---------------------+
      |    2 | ["color", "fabric"] |
      |    3 | ["color", "shape"]  |
      +------+---------------------+
      2 rows in set (0.00 sec)
    • JSON_OBJECTAGG(keyvalue) [over_clause]

      将两个列名或表达式作为参数,其中第一个用作键,第二个用作值,并返回包含键值对的JSON对象。返回NULL如果结果不包含任何行,或在错误的事件。如果任何键名为NULL或参数数目不等于2,则会发生错误

      从MySQL 8.0.14开始,此函数作为窗口函数(如果over_clause存在)执行。over_clause第12.21.2节“窗口函数的概念和语法”中所述

      mysql> SELECT o_id, attribute, value FROM t3;
      +------+-----------+-------+
      | o_id | attribute | value |
      +------+-----------+-------+
      |    2 | color     | red   |
      |    2 | fabric    | silk  |
      |    3 | color     | green |
      |    3 | shape     | square|
      +------+-----------+-------+
      4 rows in set (0.00 sec)
      
      mysql> SELECT o_id, JSON_OBJECTAGG(attribute, value)
           > FROM t3 GROUP BY o_id;
      +------+---------------------------------------+
      | o_id | JSON_OBJECTAGG(attribute, value)      |
      +------+---------------------------------------+
      |    2 | {"color": "red", "fabric": "silk"}    |
      |    3 | {"color": "green", "shape": "square"} |
      +------+---------------------------------------+
      2 rows in set (0.00 sec)

      重复的密钥处理。  当此功能的结果归一化时,具有重复键的值将被丢弃。JSON不允许重复键的MySQL数据类型规范保持一致,在返回的对象中,该键仅使用遇到的最后一个值(最后重复键获胜)。这意味着在a的列上使用此函数的结果SELECT可能取决于行的返回顺序,这是不能保证的。

      当用作窗口功能时,如果一帧中有重复的键,则结果中仅显示该键的最后一个值。如果ORDER BY规范保证这些值具有特定顺序,则帧中最后一行的键的值是确定性的如果不是,则键的结果值是不确定的。

      考虑以下:

      mysql> CREATE TABLE t(c VARCHAR(10), i INT);
      Query OK, 0 rows affected (0.33 sec)
      
      mysql> INSERT INTO t VALUES ('key', 3), ('key', 4), ('key', 5);
      Query OK, 3 rows affected (0.10 sec)
      Records: 3  Duplicates: 0  Warnings: 0
      
      mysql> SELECT c, i FROM t;
      +------+------+
      | c    | i    |
      +------+------+
      | key  |    3 |
      | key  |    4 |
      | key  |    5 |
      +------+------+
      3 rows in set (0.00 sec)
      
      mysql> SELECT JSON_OBJECTAGG(c, i) FROM t;
      +----------------------+
      | JSON_OBJECTAGG(c, i) |
      +----------------------+
      | {"key": 5}           |
      +----------------------+
      1 row in set (0.00 sec)
      
      mysql> DELETE FROM t;
      Query OK, 3 rows affected (0.08 sec)
      
      mysql> INSERT INTO t VALUES ('key', 3), ('key', 5), ('key', 4);
      Query OK, 3 rows affected (0.06 sec)
      Records: 3  Duplicates: 0  Warnings: 0
      
      mysql> SELECT c, i FROM t;
      +------+------+
      | c    | i    |
      +------+------+
      | key  |    3 |
      | key  |    5 |
      | key  |    4 |
      +------+------+
      3 rows in set (0.00 sec)
      
      mysql> SELECT JSON_OBJECTAGG(c, i) FROM t;
      +----------------------+
      | JSON_OBJECTAGG(c, i) |
      +----------------------+
      | {"key": 4}           |
      +----------------------+
      1 row in set (0.00 sec)

      从上一个查询中选择的键是不确定的。如果您希望使用特定的键顺序,则可以JSON_OBJECTAGG()通过在OVER子句中添加一个带有ORDER BY规范子句来将 特定的键强加给帧行,从而将其作为窗口函数来调用 以下示例显示了ORDER BY 在几种不同的框架规格下有无情况下会发生什么

      如果不使用ORDER BY,则框架是整个分区:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER () AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 4}  |
      | {"key": 4}  |
      | {"key": 4}  |
      +-------------+

      使用ORDER BY,其中框架是默认框架RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW(按升序和降序排列):

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i) AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 3}  |
      | {"key": 4}  |
      | {"key": 5}  |
      +-------------+
      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i DESC) AS json_object FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      | {"key": 4}  |
      | {"key": 3}  |
      +-------------+

      使用ORDER BY和整个分区的显式框架:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i
                  ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
              AS json_object
             FROM t;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      | {"key": 5}  |
      | {"key": 5}  |
      +-------------+

      要返回特定的键值(例如最小或最大),请LIMIT在适当的查询中包括一个子句。例如:

      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i) AS json_object FROM t LIMIT 1;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 3}  |
      +-------------+
      mysql> SELECT JSON_OBJECTAGG(c, i)
             OVER (ORDER BY i DESC) AS json_object FROM t LIMIT 1;
      +-------------+
      | json_object |
      +-------------+
      | {"key": 5}  |
      +-------------+

      有关其他信息和示例请参见JSON值的规范化,合并和自动包装

    • MAX([DISTINCT] expr) [over_clause]

      返回的最大值 expr。 MAX()可以采用字符串参数;在这种情况下,它将返回最大字符串值。请参见第8.3.1节“ MySQL如何使用索引”的 DISTINCT关键字可用于以找到最大的不同值中的 expr,然而,这会产生相同的结果省略DISTINCT

      如果没有匹配的行,则 MAX()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述不能与一起使用DISTINCT

      mysql> SELECT student_name, MIN(test_score), MAX(test_score)
             FROM student
             GROUP BY student_name;

      对于MAX(),MySQL当前根据字符串值而不是字符串在集合中的相对位置来比较ENUM和 SET列。这与ORDER BY 比较它们的方式不同

    • MIN([DISTINCT] expr) [over_clause]

      返回的最小值 expr。 MIN()可以采用字符串参数;在这种情况下,它将返回最小字符串值。请参见第8.3.1节“ MySQL如何使用索引”的 DISTINCT关键字可用来找到最小的不同值中的 expr,然而,这会产生相同的结果省略DISTINCT

      如果没有匹配的行,则 MIN()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述不能与一起使用DISTINCT

      mysql> SELECT student_name, MIN(test_score), MAX(test_score)
             FROM student
             GROUP BY student_name;

      对于MIN(),MySQL当前根据字符串值而不是字符串在集合中的相对位置来比较ENUM和 SET列。这与ORDER BY 比较它们的方式不同

    • STD(expr) [over_clause]

      返回的总体标准差 expr。 STD()是标准SQL函数的同义词 STDDEV_POP(),作为MySQL扩展提供。

      如果没有匹配的行,则 STD()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • STDDEV(expr) [over_clause]

      返回的总体标准差 expr。 STDDEV()是标准SQL函数的同义词 STDDEV_POP(),为与Oracle兼容而提供。

      如果没有匹配的行,则 STDDEV()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • STDDEV_POP(expr) [over_clause]

      返回expr(的平方根 VAR_POP()的总体标准偏差 您也可以使用 STD()或 STDDEV(),它们是等效的,但不是标准的SQL。

      如果没有匹配的行,则 STDDEV_POP()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • STDDEV_SAMP(expr) [over_clause]

      返回expr(的平方根 的样本标准偏差 VAR_SAMP()

      如果没有匹配的行,则 STDDEV_SAMP()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • SUM([DISTINCT] expr) [over_clause]

      返回的总和expr如果返回集没有行,则SUM() 返回NULL的 DISTINCT关键字可用来仅求和的不同的值expr

      如果没有匹配的行,则 SUM()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述不能与一起使用DISTINCT

    • VAR_POP(expr) [over_clause]

      返回的总体标准方差 expr它把行视为整体,而不是样本,因此它以行数作为分母。您也可以使用 VARIANCE(),它是等效的,但不是标准的SQL。

      如果没有匹配的行,则 VAR_POP()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • VAR_SAMP(expr) [over_clause]

      返回的样本方差 expr也就是说,分母是行数减一。

      如果没有匹配的行,则 VAR_SAMP()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    • VARIANCE(expr) [over_clause]

      返回的总体标准方差 expr。 VARIANCE()是标准SQL函数的同义词 VAR_POP(),作为MySQL扩展提供。

      如果没有匹配的行,则 VARIANCE()返回 NULL

      如果over_clause存在,此功能将作为窗口功能执行 。 over_clause如 第12.21.2节“窗口函数的概念和语法”中所述

    •  

    如有错误,恳求读者指出,发送到wu13213786609@outlook.com。
  • 相关阅读:
    MSER
    resize和reserve的区别
    Rect
    U盘文件或目录损坏且无法读取怎么解决
    信道估计
    ann
    仿射变换详解 warpAffine
    opencv新版本的数据结构
    大津法
    php红包
  • 原文地址:https://www.cnblogs.com/WLCYSYS/p/14616999.html
Copyright © 2011-2022 走看看