简体   繁体   English

以下SQL查询有什么问题?

[英]What's wrong with the following SQL query?

I have the following SQL query which finds the name and age of the oldest snowboarders. 我有以下SQL查询,用于查找最古老的滑雪板的名称和年龄。

SELECT c.cname, MAX(c.age)  
FROM Customers c  
WHERE c.type = 'snowboard';

But the guide I am reading says that query is wrong because the non-aggregate columns in the SELECT clause must come from the attributes in the GROUP BY clause. 但是我正在阅读的指南说查询是错误的,因为SELECT子句中的非聚合列必须来自GROUP BY子句中的属性。

I think this query serves its purpose because the aggregate MAX(c.age) corresponds to a single value. 我认为此查询可达到其目的,因为汇总的MAX(c.age)对应于单个值。 It does find the age of the oldest snowboarder. 它确实找到了最古老的滑雪板的年龄。

You need to group by c.cname column. 您需要按c.cname列进行分组。 Whenever you do any aggregation on some column like SUM, COUNT, etc. you need to provide another column(s) by which you want to aggregate. 每当您对某些列(例如SUM,COUNT等)进行任何汇总时,您都需要提供要汇总的另一列。 You generally provide these columns in your SELECT clause(here c.cname ). 通常,您可以在SELECT子句(此处为c.cname )中提供这些列。 These same columns should be mentioned in the GROUP BY clause else you will get a syntax error. 这些相同的列应在GROUP BY子句中提及,否则会出现语法错误。

The form should be 表格应为

SELECT A, B, C, SUM(D)
FROM TABLE_NAME
GROUP BY A, B, C;

Your query should be like below 您的查询应如下所示

SELECT  c.cname,    MAX(c.age)  
FROM    Customers   c  
WHERE   c.type=‘snowboard’
GROUP BY c.cname;

If you want to display the name and age of the oldest snowboarder(s), you have to do this: 如果要显示最古老的滑雪者的姓名和年龄,则必须执行以下操作:

SELECT  c.cname, c.age
FROM    Customers   c  
WHERE   c.type = 'snowboard'
AND c.age = (SELECT MAX(age)
             FROM Customers
             WHERE type = 'snowboard')

Whenever some other table attributes are selected along with the aggregate function then it has to be accompanied by group by clause, otherwise a situation may occur where database may not know which row has to be selected. 每当与聚合函数一起选择其他一些表属性时,它都必须带有group by子句,否则可能发生数据库可能不知道必须选择哪一行的情况。 Let us say in your example there are two customers who have same maximum age, now database will try to pull out the age from both the rows but it will get confused, which name to pick. 让我们说在您的示例中,有两个客户具有相同的最大年龄,现在数据库将尝试从两行中提取年龄,但是会感到困惑,该选择哪个名称。 Here your group by clause comes into picture, which will instruct to display two different rows with different customer names but same maximum age. 在这里,您的group by子句变成图片,它将指示显示两个不同的行,这些行具有不同的客户名称,但最大使用期限相同。 Thus, your query should look like this: 因此,您的查询应如下所示:

SELECT  c.cname,    MAX(c.age)  
FROM    Customers   c  
WHERE   c.type=‘snowboard’
GROUP BY c.cname;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM