Mysql 查询使用 where 和 group by 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2324879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql query using where and group by clause
提问by S.PRATHIBA
I have the following table.
我有下表。
mysql> select * from consumer9;
+------------+--------------+-------------------+
| Service_ID | Service_Type | consumer_feedback |
+------------+--------------+-------------------+
| 100 | Computing | -1 |
| 35 | Printer | 0 |
| 73 | Computing | -1 |
| 50 | Data | 0 |
+------------+--------------+-------------------+
I want to use GROUP BY
clause in my project. I am getting an error when I am using the query:
我想GROUP BY
在我的项目中使用子句。使用查询时出现错误:
SELECT Service_ID, Service_Type, SUM(consumer_feedback)
FROM consumer9
GROUP BY Service_ID
WHERE Service_Type=Printer;
Error
错误
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where Service_Type=Printer' at line 1
ERROR 1064 (42000):您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“where Service_Type=Printer”附近使用的正确语法
回答by a'r
The following query should work.
以下查询应该有效。
select Service_ID, Service_Type, sum(consumer_feedback)
from consumer9
where Service_Type=Printer
group by Service_ID, Service_Type;
Remember, the where clause goes before the group by clause and all non-aggregated terms in the select part will have to be present in the group by clause.
请记住,where 子句位于 group by 子句之前,并且 select 部分中的所有非聚合术语都必须出现在 group by 子句中。
回答by Emiliano Schiano
Use the having
clause instead of where
使用having
子句代替where
SELECT Service_ID, Service_Type, SUM(consumer_feedback)
FROM consumer9
GROUP BY Service_ID
HAVING Service_Type='Printer';
Regards.
问候。