汇总SQL结果的结果

时间:2014-01-07 21:04:49

标签: sql oracle aggregate-functions

我正在尝试汇总一些结果,但我没有运气。这是我正在使用的SQL和实际输出:

生成此数据的SQL语句:

SELECT 
    i.inventory_item_id, 
    i.organization_id, 
    sum(primary_transaction_quantity) as on_hand_qty
FROM mtl_onhand_quantities_detail oqd, mtl_system_items_b i
WHERE oqd.inventory_item_id = i.inventory_item_id
    AND oqd.inventory_item_id = 117567 -- just used to restrict results for this example
    AND i.organization_id = :p_organization_id
    AND oqd.organization_id = i.organization_id
GROUP BY i.inventory_item_id, i.organization_id, primary_transaction_quantity


INVENTORY_ITEM_ID,ORGANIZATION_ID,ON_HAND_QTY
117567,7651,2
117567,7651,1

我需要回复:

INVENTORY_ITEM_ID,ORGANIZATION_ID,ON_HAND_QTY
117567,7651,3

基本上,如果on_hand_qtyinventory_item_id相同,则需要对organization_id求和,并且只返回一行结果。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

好的,所以你遇到的主要问题是你在GROUP BY中包含了汇总语句,所以你的查询应该是这样的。

SELECT 
    i.inventory_item_id, 
    i.organization_id, 
    sum(primary_transaction_quantity) as on_hand_qty
FROM mtl_onhand_quantities_detail oqd, mtl_system_items_b i
WHERE oqd.inventory_item_id = i.inventory_item_id
    AND oqd.inventory_item_id = 117567 -- just used to restrict results for this example
    AND i.organization_id = :p_organization_id 
    AND oqd.organization_id = i.organization_id
GROUP BY i.inventory_item_id, i.organization_id

不确定您使用的是哪个DBMS但是如果您在谷歌上查找分组,您应该找到有关它如何工作的许多解释。

现在让我们继续你的下一个问题。您正在使用pre ansi-92连接语法。这是bad

您的代码应如下所示。

SELECT 
    i.inventory_item_id, 
    i.organization_id, 
    sum(primary_transaction_quantity) as on_hand_qty
FROM mtl_onhand_quantities_detail oqd
INNER JOIN mtl_system_items_b i
    ON oqd.inventory_item_id = i.inventory_item_id
    AND oqd.organization_id = i.organization_id
    AND i.organization_id = :p_organization_id --Added back the function now that I know it isn't a typo
WHERE 
    oqd.inventory_item_id = 117567 -- just used to restrict results for this example
GROUP BY i.inventory_item_id, i.organization_id

答案 1 :(得分:0)

从子组中删除primary_transaction_quantity