2014-01-07 240 views
0

我想彙總一些結果,但我沒有任何運氣。下面是我使用的SQL與實際輸出:它生產這個數據從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_qty並且只返回一個結果行,如果inventory_item_idorganization_id是相同的。任何幫助是極大的讚賞!從組

+0

什麼是:p_organization_id? – Zane

+1

您還使用了哪些DBMS? – Zane

+0

:p_organization_id是您如何在Oracle中定義用戶可以在報表運行時輸入的參數。它們輸入的值被替換,其中:p_organization_id在代碼中。 – Jedis

回答

0

刪除primary_transaction_quantity by子句

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 
+0

非常感謝。我使用Oracle作爲DBMS。 不幸的是,這只是報告的一個非常小的子集,它使用了較舊的連接語法。爲了保持整個報告的一致性,我保持這種狀態。我不知道如何改寫其餘部分以使用其他方式? – Jedis

+0

這可能很困難,但從長遠來看,這是正確的方式。如果你有時間,我強烈建議轉換舊的代碼。如果沒有別的,這是很好的做法。 :) – Zane