SUM(a * b)有什么作用?

时间:2012-04-19 21:54:16

标签: mysql sql group-by

我以前从未见过SUM(a * b)。我希望有人可以告诉我它的预期行为,以及它是否是SQL标准的一部分,或MySQL恰好实现的东西。一个例子:

localhost test> CREATE TABLE numbers (id int not null primary key auto_increment, a int, b int);
Query OK, 0 rows affected (0.03 sec)

localhost test> INSERT INTO numbers (a,b) VALUES (1, 2), (3,4),(1,1),(5,6);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

localhost test> select * FROM numbers GROUP BY id;
+----+------+------+
| id | a    | b    |
+----+------+------+
|  1 |    1 |    2 |
|  2 |    3 |    4 |
|  3 |    1 |    1 |
|  4 |    5 |    6 |
+----+------+------+
4 rows in set (0.00 sec)

localhost test> select SUM(a), SUM(b) FROM numbers GROUP BY id;
+--------+--------+
| SUM(a) | SUM(b) |
+--------+--------+
|      1 |      2 |
|      3 |      4 |
|      1 |      1 |
|      5 |      6 |
+--------+--------+
4 rows in set (0.00 sec)

localhost test> select SUM(a*b), SUM(a), SUM(b) FROM numbers GROUP BY id;
+----------+--------+--------+
| SUM(a*b) | SUM(a) | SUM(b) |
+----------+--------+--------+
|        2 |      1 |      2 |
|       12 |      3 |      4 |
|        1 |      1 |      1 |
|       30 |      5 |      6 |
+----------+--------+--------+
4 rows in set (0.00 sec)

localhost test> alter table numbers add col2 int not null;
Query OK, 4 rows affected (0.03 sec)
Records: 4  Duplicates: 0  Warnings: 0

localhost test> update numbers set col2 = id %2;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 4  Changed: 2  Warnings: 0

localhost test> select col2, SUM(a*b), SUM(a), SUM(b) FROM numbers GROUP BY col2;
+------+----------+--------+--------+
| col2 | SUM(a*b) | SUM(a) | SUM(b) |
+------+----------+--------+--------+
|    0 |       42 |      8 |     10 |
|    1 |        3 |      2 |      3 |
+------+----------+--------+--------+
2 rows in set (0.01 sec)

我预计最后一行会有80和30,或者如果它使用MySQL的非标准行为选择一行(我启用了SQL_MODE = ONLY_FULL_GROUP_BY),则会产生错误。

1 个答案:

答案 0 :(得分:6)

表达式SUM(a*b)是完全有效的标准SQL。它计算每行的a * b,并对每个组内的结果求和(如果没有指定GROUP BY,则对整个表进行求和)。

+----+------+------+------+-----+
| id | col2 | a    | b    | a*b |
+----+------+------+------+-----+
|  1 |    1 |    1 |    2 |   2 |                  
|  2 |    0 |    3 |    4 |  12 |  --+
|  3 |    1 |    1 |    1 |   1 |    |---> 12 + 30 = 42
|  4 |    0 |    5 |    6 |  30 |  --+
+----+------+------+------+-----|

SUM(a) * SUM(b)相同。