【问题标题】:SQL selecting the maximum value of multiple items with all the columnsSQL选择所有列的多个项目的最大值
【发布时间】:2022-01-15 03:01:45
【问题描述】:

数据:

我的查询:

SELECT 
    itemcode, whsecode, MAX(quantity)
FROM
    inventoryTable
GROUP BY 
    itemcode;

这会返回这个错误:

列 'inventoryTable.whsecode' 在选择列表中无效,因为 它不包含在聚合函数或 GROUP BY 中 子句。

当我将 whsecode 放在 GROUP BY 子句中时,它只是返回表中的所有数据。

我想要的输出是返回其中项目数量最多的 whsecode。 它应该有的输出是:

whsecode|itemcode|quantity
 WHSE2  |  SS585 |  50
 WHSE2  |  SS586 |  50
 WHSE1  |  SS757 |  30

最终我会将该查询放入另一个查询中:

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, MAX(quantity) AS whseqty
    FROM inventoryTable
    GROUP BY itemcode, whsecode
) C ON B.itemcode = C.itemcode
INNER JOIN 
    Items D ON B.itemcode = D.itemcode
WHERE 
    A.mrno = @MRNo AND B.quantity < C.whseqty;

使用 GROUP BY 子句中的 whsecode,输出为:

但正如我之前所说,问题在于它返回多行相同的 itemcode。它应该有的输出是:

     mrno      | remarks| itemcode|           description          | uom  |quantity|whsecode|whseqty|  rate
MR211100003008 | SAMPLE | FG 4751 | LONG DRILL 3.4 X 200 L550      | PCS. |  50.00 | WHSE3  | 100   | 0.0000
MR211100003008 | SAMPLE | FG 5092 | T-SPIRAL TAP M3.0 X 0.5 L6904  | PCS  |  20.00 | WHSE1  | 80    | 0.0000

我不确定B.quantity &lt; C.whseqty 是否应该在那里,但它消除了不是最大值的其他值。

【问题讨论】:

标签: sql join select group-by max


【解决方案1】:

有很多方法可以解决这个问题。例如,通过使用the ROW_NUMBER function:

SELECT
    itemcode,
    whsecode, 
    quantity As whseqty
FROM
(
    SELECT 
        itemcode, 
        whsecode, 
        quantity,
        ROW_NUMBER() OVER (PARTITION BY itemcode ORDER BY quantity DESC) As RN
    FROM
        inventoryTable
)
WHERE
    RN = 1
;

【讨论】:

    【解决方案2】:

    编辑:

    select whsecode,A.itemcode,qty from inventoryTable  
    join (SELECT itemcode, MAX(quantity) as qty FROM inventoryTable GROUP BY itemcode) as A on A.itemcode = inventoryTable.itemcode and A.qty = inventoryTable.quantity  
    

    【讨论】:

    • 我认为这不能正常工作。考虑一下如果您的数据有A: 1A: 2B: 1 会发生什么;将返回所有三行,即使 A: 1 应该被排除在外。
    • 我编辑了我的答案,谢谢你的警告
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2016-01-04
    • 2020-05-03
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    相关资源
    最近更新 更多