SQL 选择所有列的最大值
SQL selecting the maximum value with all the column
查询:
SELECT
itemcode, whsecode, MAX(quantity)
FROM
inventoryTable
WHERE
itemcode = 'FG 4751'
GROUP BY
itemcode;
它returns这个错误:
Column 'inventoryTable.whsecode' is invalid in the select list because
it is not contained in either an aggregate function or the GROUP BY
clause.
当我将 whsecode 放在 GROUP BY 子句中时,它只是 returns 所有或多行带有项目代码 'FG 4751'
:
我需要的输出是
FG 4751|WHSE3|100
SELECT TOP 1 *
FROM inventoryTable
WHERE itemcode = 'FG 4751'
ORDER BY quantity DESC
理查德-
不确定是否计划在某个时候将其用于多个项目代码。这可以使用 window 函数 -
来实现
WITH HIGH_RANK AS(
SELECT
itemcode,
whsecode,
quantity,
RANK(quantity) OVER (PARTITION BY itemcode ORDER BY quantity DESC) AS MAX_RANK
FROM
inventoryTable)
SELECT
itemcode,
whsecode,
quantity
FROM HIGH_RANK
WHERE MAX_RANK = 1
-RANK(数量) OVER (PARTITION BY itemcode ORDER BY quantity DESC) AS MAX_RANK
在所有数量等于最大值的情况下,使用等级将离开,如果您只想要一个值,请将 RANK 换成 ROW_NUMBER
SELECT * FROM inventoryTable
WHERE itemcode = 'FG 4751'
ORDER BY MAX(quantity) DESC LIMIT 1
查询:
SELECT
itemcode, whsecode, MAX(quantity)
FROM
inventoryTable
WHERE
itemcode = 'FG 4751'
GROUP BY
itemcode;
它returns这个错误:
Column 'inventoryTable.whsecode' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
当我将 whsecode 放在 GROUP BY 子句中时,它只是 returns 所有或多行带有项目代码 'FG 4751'
:
我需要的输出是
FG 4751|WHSE3|100
SELECT TOP 1 *
FROM inventoryTable
WHERE itemcode = 'FG 4751'
ORDER BY quantity DESC
理查德-
不确定是否计划在某个时候将其用于多个项目代码。这可以使用 window 函数 -
来实现WITH HIGH_RANK AS(
SELECT
itemcode,
whsecode,
quantity,
RANK(quantity) OVER (PARTITION BY itemcode ORDER BY quantity DESC) AS MAX_RANK
FROM
inventoryTable)
SELECT
itemcode,
whsecode,
quantity
FROM HIGH_RANK
WHERE MAX_RANK = 1
-RANK(数量) OVER (PARTITION BY itemcode ORDER BY quantity DESC) AS MAX_RANK
在所有数量等于最大值的情况下,使用等级将离开,如果您只想要一个值,请将 RANK 换成 ROW_NUMBER
SELECT * FROM inventoryTable
WHERE itemcode = 'FG 4751'
ORDER BY MAX(quantity) DESC LIMIT 1