简体   繁体   English

MS Access SQL 查询

[英]MS Access SQL Query

I am new to SQL and attempting to display a max value from a column as well as display a separate column from the same table, however, my query doesn't work.我是 SQL 新手,并试图显示列中的最大值以及显示同一表中的单独列,但是,我的查询不起作用。

Here is my code:这是我的代码:

    SELECT ProductName, ProductPrice, MAX(ProductPrice) AS MostProfitable
    FROM tblProducts;

I receive this error:我收到此错误:

"Your query does not include the specified expression 'ProductName' as part of an aggregate function." “您的查询不包括指定的表达式 'ProductName' 作为聚合函数的一部分。”

Please Help!请帮忙!

A simple method to get all the columns to use ORDER BY and TOP :让所有列使用ORDER BYTOP简单方法:

SELECT TOP (1) p.*
FROM tblProducts as p 
ORDER BY p.ProductPrice DESC;

Note that TOP in MS Access can return more rows if there are ties.请注意,如果有关系,MS Access 中的TOP可以返回更多行。 If you want only one row, then include an additional key in the ORDER BY to prevent ties:如果您只需要一行,则在ORDER BY包含一个额外的键以防止联系:

ORDER BY p.ProductPrice DESC, p.ProductName;

You don't need any aggregation function just get it like below:您不需要任何聚合函数,只需像下面这样获取它:

SELECT TOP(1) ProductName, ProductPrice
FROM tblProducts
ORDER BY ProductPrice DESC;

None of the functions of column would work until you GROUP your rows.在您对行进行分组之前,列的任何功能都不会起作用。

That is, your MAX() function will not work because you have not used GROUP.也就是说,您的 MAX() 函数将不起作用,因为您没有使用 GROUP。

Here is the SQL that should work:这是应该工作的SQL:

SELECT ProductName, ProductPrice, MAX(ProductPrice) AS MostProfitable
FROM tblProducts GROUP BY ProductName;

I would suggest you to add your Product ID in your SQL query and GROUP the query on it.我建议您在您的 SQL 查询中添加您的产品 ID,并将查询分组。 But for the instance, I have grouped your query on ProductName.但是,例如,我已将您的查询分组到 ProductName 上。

Remember, its not professional.记住,它不是专业的。 Because different products having same name will also be combined to show one MAX value.因为具有相同名称的不同产品也会组合在一起显示一个 MAX 值。

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

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