如何使用sum函数进行查询分组

时间:2015-05-23 13:05:02

标签: sql-server sql-server-2012

我在SQL Server中有inventoryTransaction表就像这样:

productID StockLocationID TransactionType   Quantity
1046          1                "in"           100
1046          1               "out"            20
1046          2                "in"            70
1046          2               "out"            65
...

如何进行查询,输出如下:

productID  StockLocationID     stock
1046          1                 80
1046          2                 5

2 个答案:

答案 0 :(得分:3)

您可以尝试:

SELECT 
    productID, 
    StockLocationID,
    SUM(CASE 
            WHEN TransactionType = 'out' THEN -1 
            ELSE 1 
        END) * Quantity) AS stock
GROUP BY 
    productID, 
    StockLocationID

答案 1 :(得分:1)

同样但稍微缩短了消除不必要的乘法:

SELECT 
    productID, 
    StockLocationID,
    SUM(CASE TransactionType 
            WHEN 'out' THEN -Quantity 
            ELSE Quantity 
        END) AS stock
GROUP BY 
    productID, 
    StockLocationID