GroupBy Sql查询asp.net时出错

时间:2018-03-20 10:54:37

标签: sql ms-access

我正在尝试做的查询是从OrderDetails中查询所有帐户购买的项目将它们排成一行并向我显示从任何产品中购买了多少,我要做的是显示itemname和项目图像 不仅仅是身份和总和 这是我做的查询:

string strSql = "SELECT Sum(OrderDetails.ItemStock),OrderDetails.ItemID,Items.ItemName,Items.ItemImage FROM OrderDetails,Items WHERE OrderDetails.ItemID = Items.ItemID GROUP BY OrderDetails.ItemID ORDER BY SUM(OrderDetails.ItemStock) DESC";

我从此查询中获得的错误: “查询不包含指定短语'ItemName'作为聚合函数的一部分。”

当我写这样的查询时:

  string strSql = "SELECT Sum(OrderDetails.ItemStock),OrderDetails.ItemID FROM OrderDetails GROUP BY OrderDetails.ItemID ORDER BY SUM(OrderDetails.ItemStock) DESC";

没关系

2 个答案:

答案 0 :(得分:3)

错误消息"The query does not include the specified phrase 'ItemName' as part of an aggregate function."清楚地表明您需要包含ItemName子句中缺少的列group by

根据您在select语句中的列,您查询的内容应如下所示,其中未应用聚合函数的所有列都包含在group by子句中。这是sql。{/ p>中group by子句的要求

string strSql = "SELECT Sum(OrderDetails.ItemStock),
    OrderDetails.ItemID,Items.ItemName,Items.ItemImage
    FROM OrderDetails,Items
    WHERE OrderDetails.ItemID = Items.ItemID
    GROUP BY OrderDetails.ItemID,,Items.ItemName,Items.ItemImage
        ORDER BY SUM(OrderDetails.ItemStock) DESC";

答案 1 :(得分:1)

学习使用明确的JOIN语法!并且,修复您的聚合:

SELECT SUM(od.ItemStock), od.ItemID, i.ItemName, i.ItemImage
FROM OrderDetails as od INNER JOIN
     Items as i
     ON od.ItemID = i.ItemID
GROUP BY od.ItemID, i.ItemName, i.ItemImage
ORDER BY SUM(od.ItemStock) DESC;

对您的问题的修复只是在GROUP BY中包含所有非聚合列。但是你应该学习如何编写干净的SQL。