计算多行

时间:2014-01-21 16:18:35

标签: mysql sql sql-server select hana

我有以下输入表:

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

我需要计算库存价值数量的加权平均价格。 例如, 所有选定行的库存*价格除以总数。库存编号。数学上,

  

((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

如何扩展/修改select语句以获得以下输出:

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

3 个答案:

答案 0 :(得分:1)

您无法使用(库存*价格)/总和(库存),因为您没有按库存列进行分组。您只能使用sum(Inventory)等灌溉函数。

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

答案 1 :(得分: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

答案 2 :(得分:0)

删除不打算分组的列,并获取NetPrice的MAX。

但是,它可以在MySQL中运行,但不适用于MSSQL,因为它需要在GROUP BY子句中使用Store和Supplier。如果从输出中删除这些列,则应该使它在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