2012-04-19 230 views
1

我從來沒有見過SUM(a * b)。我希望有人能告訴我它的預期行爲,以及它是否是SQL標準的一部分,或者是MySQL恰好實現的。舉個例子:SUM(a * b)做什麼?

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啓用)。

回答

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)

+0

太棒了。謝謝你,先生! – 2012-04-19 22:13:29

相關問題