2014-01-21 40 views
0

我有以下的輸入表:計算在多行

Article Store Supplier NetPrice Pieces Sum Inventory Price   Cond 
NL1234 N001 3100000 161,5  2  323 7   123,45   2,47 
NL1234 N001 3100000 161,5  0  0  4   103,8   2,08 
NL1234 N001 3100000 161,5  0  0  23   120,8   1,21 

我需要計算價格的加權平均存貨價值的數量。 例如, 所有選定行的庫存*價格除以總數量。庫存number.Mathematically的,

((7 * 123.45)+(4 * 103.8)+(120.8))/(34)

SELECT 
    Article, 
    Store, 
    Supplier, 
    NetPrice, 
    sum(Pieces) as "Pieces", 
    sum(Sum) as "Sum", 
    sum(Inventory) as "Inventory", 
    (Inventory*Price)/sum(Inventory) as "Price", 
    (Inventory*Cond)/sum(Inventory) as "Cond" 
FROM 
    table_name 
WHERE 
    "Article" = 'NL1234' 
GROUP BY 
    STORE, 
    SUPPLIER, 
    NetPrice, 
    Article 

如何可以擴展/修改我的選擇聲明以獲得以下輸出:

Article Store Supplier NetPrice Pieces Sum Inventory Price Cond 
NL1234 N001 3100000 161,5  2  323 34   119,35 1,57 
+0

MySQL或SQL服務器? – Mihai

+0

任何事情,我只是無法得到這樣做的邏輯。如果你能幫助我,那麼我會非常感激 –

+1

你的查詢應該已經產生了這個結果。你有什麼問題? – 2014-01-21 16:23:07

回答

1

您無法使用(庫存*價格)/總和(庫存),因爲您沒有按庫存列分組。您只能使用sum(庫存)等灌溉功能。

SELECT 
    Article, 
    SUM(Pieces) as "Pieces", 
    SUM(Sum) as "Sum", 
    SUM(Inventory) as "Inventory", 
    SUM(Inventory * Price)/SUM(Inventory) as "Price", 
    SUM(Inventory * Cond)/SUM(Inventory) as "Cond" 
FROM 
    table_name 
WHERE 
    "Article" = 'NL1234' 
GROUP BY 
    Article 
+0

上的總和聚合,你可以舉一個例子這個?我認爲你的建議是正確的。我得到了同樣的錯誤 –

+0

@SangameshHs我更新了quey,試試這個 – Backs

0

刪除你不打算分組的列,並得到MAX的NetPrice。

但是,它將在MySQL中工作,但不在MSSQL上,因爲它需要在GROUP BY子句中存儲和供應商。如果你從輸出中刪除這些列,你也應該使用MSSQL。

SELECT 
    Article, 
    Store, 
    Supplier, 
    MAX(NetPrice), 
    sum(Pieces) as "Pieces", 
    sum(Sum) as "Sum", 
    sum(Inventory) as "Inventory", 
    (Inventory*Price)/sum(Inventory) as "Price", 
    (Inventory*Cond)/sum(Inventory) as "Cond" 
FROM 
    table_name 
WHERE 
    "Article" = 'NL1234' 
GROUP BY 
    Article 
1

移動的行總計爲CROSS APPLY,然後使用這個結果在查詢像這樣:

SELECT Article, 
     Store, 
     Supplier, 
     MAX(NetPrice), 
     sum(Pieces) as "Pieces", 
     sum(Sum) as "Sum", 
     sum(Inventory) as "Inventory", 
     T.TotalInvCost/sum(Inventory) as "Price", 
     T.TotalInvCond/sum(Inventory) as "Cond" 
FROM table_name 
CROSS APPLY (
SELECT SUM(Inventory*Price) AS 'TotalInvCost' 
,SUM(Inventory*Cond) AS 'TotalInvCond' 
FROM table_name 
WHERE Article = 'NL1234' 
) T 
WHERE 
Article = 'NL1234' 
GROUP BY 
STORE, 
SUPPLIER, 
Article