考试报名
考试报名
考试内容
考试大纲
在线客服
返回顶部

备考刷题,请到

CDA认证小程序

There are two tables in a database. The "users" table has three fields (user_id, user_name, create_at), and the "orders" table has three fields (order_id, user_id, amount). Which of the following SQL query statements will not result in an error when executed?
A. select user_id, avg(amount) from orders where avg(amount) > 2000;
B. select user_id, avg(amount) from orders where avg(amount) > 2000;
C. select user_id, avg(amount) from orders where avg(amount) > 2000;
D. select user_id, avg(amount) from orders group by user_id having avg(amount) > 2000;
上一题
下一题
收藏
点赞
评论
题目解析
题目评论(0)

In the query statements, the WHERE clause should appear before the GROUP BY clause, and you cannot use aggregate functions in the WHERE clause.

正确答案是:D: `select user_id, avg(amount) from orders group by user_id having avg(amount) > 2000;`

专业分析:

A、B、C这三个选项的SQL查询语句都存在语法错误,因为它们在`where`子句中使用了聚合函数`avg(amount)`。在SQL中,`where`子句不能直接使用聚合函数。聚合函数通常用于`select`列表或`having`子句中。

D选项的SQL查询语句是正确的,因为它首先使用`group by`子句对`user_id`进行分组,然后在`having`子句中使用聚合函数`avg(amount)`进行过滤。`having`子句是专门用于过滤分组后的结果的,因此可以使用聚合函数。

完整的SQL查询语句解释如下:
```sql
select user_id, avg(amount)
from orders
group by user_id
having avg(amount) > 2000;
```
1. `select user_id, avg(amount)`:选择`user_id`和每个用户的订单金额的平均值。
2. `from orders`:从`orders`表中选择数据。
3. `group by user_id`:按照`user_id`进行分组。
4. `having avg(amount) > 2000`:过滤分组后的结果,只保留平均订单金额大于2000的用户。