1

我需要使用 sql Server 从简单实体中提取数据的帮助。

库存实体具有列(pk,fk)product_id, (pk,fk)warehouse_id, inventory_amount, inventory_max_stock, inventory_reorder_point

我需要库存记录作为产品 ID 列表和以下列的总和:库存数量、库存最大库存和库存再订购点。仅显示inventory_amount > 900.

SELECT PRODUCT_ID, SUM(INVEN_AMOUNT), SUM(INVEN_MAX_STOCK),
SUM(INVEN_REORDER_POINT) FROM INVENTORY
GROUP BY PRODUCT_ID HAVING INVEN_AMOUNT > 900;

那是我尝试过的代码。但我不断收到错误,即它不是按表达式分组的。关于我为什么会收到该错误的任何帮助?

4

2 回答 2

0

HAVING INVEN_AMOUNT > 900 isn't allowed since you aren't grouping by INVEN_AMOUNT. Use WHERE instead:

SELECT PRODUCT_ID, SUM(INVEN_AMOUNT), SUM(INVEN_MAX_STOCK), SUM(INVEN_REORDER_POINT)
FROM INVENTORY
WHERE INVEN_AMOUNT > 900
GROUP BY PRODUCT_ID;

If you want to limit those groups with sums > 900, then use SUM(INVEN_AMOUNT):

SELECT PRODUCT_ID, SUM(INVEN_AMOUNT), SUM(INVEN_MAX_STOCK), SUM(INVEN_REORDER_POINT)
FROM INVENTORY
GROUP BY PRODUCT_ID 
HAVING SUM(INVEN_AMOUNT) > 900;
于 2012-11-19T19:38:32.230 回答
0

INVEN_AMOUNT与 一起使用时无效having,但SUM(INVEN_AMOUNT)有效。Having用于 sum()、avg() 和 max() 等聚合函数,否则使用where更好

SELECT PRODUCT_ID, SUM(INVEN_AMOUNT) as INVEN_AMOUNT,
SUM(INVEN_MAX_STOCK), SUM(INVEN_REORDER_POINT) FROM INVENTORY
GROUP BY PRODUCT_ID Having SUM(INVEN_AMOUNT) > 900;

在这里查看

于 2012-11-19T21:12:12.830 回答