SQL报错求助:指定表达式未包含在聚合函数中
Let's break down what's going wrong and fix your query step by step:
Why You're Getting the Error
The error message Your query does not include the specified expression 'Product_Line_ID=2 OR Product_Line_ID=3' as part of an aggregate function comes down to SQL's GROUP BY rules: any non-aggregated column or expression in your SELECT clause must either be listed in the GROUP BY clause, or wrapped in an aggregate function (like COUNT(), MIN()). Your current query puts the filter condition directly in SELECT, which violates this rule.
What You Actually Need to Do
Your goal is to filter rows first to only include those where Product_Line_ID is 2 or 3, then perform your aggregations. Here's how to adjust the query:
Corrected Query
SELECT COUNT(Product_Finish) AS Total_Finished_Products, MIN(Standard_Price) AS Minimum_Standard_Price FROM Product_T WHERE Product_Line_ID IN (2, 3) -- Filter for the desired product lines FIRST AND Product_Finish IS NOT NULL -- Explicitly filter out null finishes (fixes your original vague WHERE condition) GROUP BY Standard_Price HAVING AVG(Standard_Price) < 700 ORDER BY Product_Finish; -- Fixed the typo (FInish → Finish)
Key Changes Explained
- Moved the product line filter to
WHERE: UsingProduct_Line_ID IN (2,3)is a cleaner alternative toOR, and this clause filters rows before any aggregation happens (which is more efficient). - Fixed the
Product_Finishcondition: Your originalWHERE Product_Finishis ambiguous — it evaluates to true if the value is non-null, but making it explicit withProduct_Finish IS NOT NULLmakes your intent clear. - Removed the invalid
SELECTexpression: Since you want to filter rows (not calculate a boolean for each row), we don't needProduct_Line_ID=2 OR Product_Line_ID=3in theSELECTclause anymore. - Fixed the
ORDER BYtypo:Product_FInishhad a capitalization error; corrected toProduct_Finish.
If You Want to Include a Product Line Indicator
If you actually wanted to show a flag for whether the group falls into lines 2/3 (alongside aggregations), you'd need to wrap that expression in an aggregate function or add it to GROUP BY. For example:
SELECT CASE WHEN Product_Line_ID IN (2,3) THEN 'Yes' ELSE 'No' END AS Is_Target_Line, COUNT(Product_Finish) AS Total_Finished_Products, MIN(Standard_Price) AS Minimum_Standard_Price FROM Product_T WHERE Product_Finish IS NOT NULL GROUP BY Standard_Price, CASE WHEN Product_Line_ID IN (2,3) THEN 'Yes' ELSE 'No' END HAVING AVG(Standard_Price) < 700 ORDER BY Product_Finish;
内容的提问来源于stack exchange,提问作者nmahesh

