Mysql 查询使用 where 和 group by 子句

标签 mysql

我有下表。

mysql> select * from consumer9;
+------------+--------------+-------------------+
| Service_ID | Service_Type | consumer_feedback |
+------------+--------------+-------------------+
|        100 | Computing    |                -1 |
|         35 | Printer      |                 0 |
|         73 | Computing    |                -1 |
|         50 | Data         |                 0 |
+------------+--------------+-------------------+

我想在我的项目中使用GROUP BY子句。我在使用查询时遇到错误:

SELECT  Service_ID, Service_Type, SUM(consumer_feedback) 
FROM consumer9 
GROUP BY Service_ID 
WHERE Service_Type=Printer;

错误

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

最佳答案

以下查询应该有效。

select Service_ID, Service_Type, sum(consumer_feedback) 
from consumer9 
where Service_Type=Printer
group by Service_ID, Service_Type;

请记住,where 子句位于 group by 子句之前,并且 select 部分中的所有非聚合术语都必须出现在 group by 子句中。

关于Mysql 查询使用 where 和 group by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52597804/

相关文章:

mysql - 更改单个数据库目录 MySQL

mysql - PHPMyadmin 中的表出现奇怪的问题

php - 选择数据标题加入详细信息最后一个 doc_num 标题是否升级?

mysql - 返回重复值数量的查询

c# - 回滚在 C# 中不起作用

asp.net - .NET 2.0 和 MySql 处于中等信任模式

php - 使用可选参数构建 SQL 语句

php - 如何从 MySQL 表数据创建 Word 文档?

mysql - MySQL生成随机经纬度

mysql - 如何在MYSQL的FROM子句中指定更新的目标表?