列 "not contained in either an aggregate function or a GROUP BY clause"

Column "not contained in either an aggregate function or a GROUP BY clause"

查询:

SELECT 
    A.mrno, A.remarks, 
    B.itemcode, B.description, B.uom, B.quantity, 
    C.whsecode, MAX(C.quantity) AS whseqty, D.rate 
FROM 
    Mrhdr A
INNER JOIN 
    Mrdtls B ON A.mrno = B.mrno
INNER JOIN 
    inventoryTable C ON B.itemcode = C.itemcode
INNER JOIN 
    Items D ON B.itemcode = D.itemcode
WHERE 
    (A.mrno = @MRNo AND B.quantity < C.quantity);

错误:

Column 'Mrhdr.mrno' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

它说列 mrno 不包含在某些聚合函数中,但是当我对它做一些事情时,比如将它放在 GROUP BY 子句中,下一列请求 return 相同的错误直到最后一列,除了 C.quantity 列,当它们都在 GROUP BY 子句中时,它只会 return 相同的输出,而不是 return 数量的最高或最大值。当我使用 MAX 或聚合函数时,我应该如何处理其他列。

以上查询的输出:

如果我将所有列放在 GROUP BY 子句中,它 return 的输出包含两个项目代码 FG 4751,它只是消除了聚合函数的错误,但我只想要最大值待 returned(仅 100 个,warehouse/inventory 中数量最多)。

将所有内容都放在 group by 子句中的替代方法是使用 window 函数。那么问题就变成了相对于什么的 MAX 值?

例如,您可以根据所有条件获取 MAX 值,这将return与分组依据相似的结果,而不会只为列留下不同的值。

SELECT 
    A.mrno, 
    A.remarks, 
    B.itemcode, 
    B.description, 
    B.uom, 
    B.quantity, 
    C.whsecode, 
    MAX(C.quantity) OVER(PARTITION BY A.mrno, A.remarks, B.itemcode, B.description, B.uom, B.quantity, C.whsecode, D.rate) AS whseqty, 
    D.rate 
FROM 
    Mrhdr A
INNER JOIN 
    Mrdtls B ON A.mrno = B.mrno
INNER JOIN 
    inventoryTable C ON B.itemcode = C.itemcode
INNER JOIN 
    Items D ON B.itemcode = D.itemcode
WHERE 
    (A.mrno = @MRNo AND B.quantity < C.quantity);

您想处理每个产品的最大库存数量。但是您要加入所有库存行,您应该只选择最大数量的行。

这可以通过横向连接来完成,如果您的 DBMS 支持它(您忘记告诉我们您正在使用哪个)或简单地通过应用 window 函数连接有问题的行,如下所示.

SELECT 
    A.mrno, A.remarks, 
    B.itemcode, B.description, B.uom, B.quantity, 
    C.whsecode, C.whseqty, D.rate 
FROM 
    Mrhdr A
INNER JOIN 
    Mrdtls B ON A.mrno = B.mrno
INNER JOIN 
(
    SELECT
      itemcode, whsecode, quantity as whseqty,
      MAX(quantity) OVER (PARTITION BY itemcode) AS max_qty
    FROM inventoryTable
) C ON B.itemcode = C.itemcode AND C.whseqty = C.max_qty
INNER JOIN 
    Items D ON B.itemcode = D.itemcode
WHERE 
    A.mrno = @MRNo AND B.quantity < C.whseqty;

此查询应该适用于大多数 DBMS。如果您正在使用支持标准 SQL FETCH WITH TIES 子句的 DBMS,我会将连接更改为:

INNER JOIN 
(
    SELECT itemcode, whsecode, quantity as whseqty
    FROM inventoryTable
    ORDER BY RANK() OVER (PARTITION BY itemcode ORDER BY quantity DESC)
    FETCH FIRST ROW WITH TIES
) C ON B.itemcode = C.itemcode

以便仅 select 子查询中的顶部行,而不是以后笨拙地过滤它们。但是,在这里甚至可以认为横向连接更直接。