我想编写这些SQL查询:
CREATE VIEW `uniaverage` AS
SELECT `averagegrade`.`mjr`,`averagegrade`.`lev`,
AVG(`averagegrade`.`average`) AS `uniAVG`
FROM `averagegrade` GROUP BY `averagegrade`.`lev`, `averagegrade`.`mjr`;
但是MySQL Query Browser给了我这个错误:
Operand Should Contain 1 column(s)
我在哪里读到我可以在超过1列使用group by !!! 我该如何解决这个错误?或者如何更改查询以获得相同的结果?
答案 0 :(得分:7)
你可以这样做:
GROUP BY CONCAT(field1, field2, field3, etc)
希望这会有所帮助..
答案 1 :(得分:7)
是的,您可以在GROUP BY子句中使用多个逗号分隔的列或表达式,就像OP一样。以the MySQL docs:
为例SELECT id, FLOOR(value/100) AS val
FROM tbl_name
GROUP BY id, val;
不要 使用CONCAT()
代替the accepted answer suggests;它会给你不正确的结果,因为CONCAT('foo', 'bar', 'baz')
和CONCAT('fo', 'obarb', 'az')
是相同的。
OP发布的SQL很好。他收到的错误消息必定是由他在查询中删除之前删除的其他内容引起的;他发布的代码不会产生他说的错误。这是证据:
mysql> CREATE TABLE averagegrade (mjr int, lev int, average int);
Query OK, 0 rows affected (0.12 sec)
mysql> INSERT INTO averagegrade VALUES (5,6,7), (5,6,7), (100, 200, 300);
Query OK, 3 rows affected (0.05 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql>
mysql> -- OP's SQL, copied verbatim:
mysql> CREATE VIEW `uniaverage` AS
-> SELECT `averagegrade`.`mjr`,`averagegrade`.`lev`,
-> AVG(`averagegrade`.`average`) AS `uniAVG`
-> FROM `averagegrade` GROUP BY `averagegrade`.`lev`, `averagegrade`.`mjr`;
Query OK, 0 rows affected (0.03 sec)
mysql>
mysql> SELECT * FROM uniaverage;
+------+------+----------+
| mjr | lev | uniAVG |
+------+------+----------+
| 5 | 6 | 7.0000 |
| 100 | 200 | 300.0000 |
+------+------+----------+
2 rows in set (0.00 sec)