1

我有一个看起来像这样的表:

+----+------+--------+----------+
| ID | Code | OpType | Quantity |
+----+------+--------+----------+
|  0 | A    | IN     |        7 |
|  1 | B    | IN     |        8 |
|  2 | A    | OUT    |        2 |
|  3 | B    | IN     |        7 |
|  4 | B    | OUT    |       12 |
+----+------+--------+----------+

我想要 SUM(Quantity) 取决于 OpType。当 OpType 为 OUT 时,Quantity 字段应乘以 -1。

查询的结果应该是:

Code   IN   OUT   Final
A      7    2     5
B      15   12    3

我试过这个,但它不起作用:

SELECT(SELECT SUM(Quantity) FROM Table WHERE OpType = 'IN') AS[IN], (SELECT SUM(Quantity) FROM Table WHERE OpType = 'OUT') AS[OUT], (SELECT SUM(Quantity) FROM Table WHERE OpType = 'IN') - (SELECT SUM(Quantity) FROM Table WHERE OpType = 'OUT') AS[Final]
FROM Table
GROUP BY Code
4

2 回答 2

1

SQL Server 具有PIVOT功能。

SELECT  [Code], [IN], [OUT], [IN] - [OUT] AS [Final]
FROM
        (
            SELECT  [Code], OpType, SUM(Quantity) Quantity
            FROM    TableName
            GROUP   BY [Code], OpType
        ) org
        PIVOT
        (
            MAX(Quantity)
            FOR OpType IN ([IN],[OUT])
        ) pvt

输出

╔══════╦════╦═════╦═══════╗
║ CODE ║ IN ║ OUT ║ FINAL ║
╠══════╬════╬═════╬═══════╣
║ A    ║  7 ║   2 ║     5 ║
║ B    ║ 15 ║  12 ║     3 ║
╚══════╩════╩═════╩═══════╝
于 2013-04-25T14:44:10.223 回答
1

我会在每列的 SUM 中使用CASE语句,以便您只对所需值求和(即,对于 IN 列,仅对 OpType='IN' 的数量求和,对于 OUT 列,仅对 OpType= 的数量求和'出去')

SELECT Code, 
    SUM(CASE WHEN OpType = 'IN' THEN Quantity ELSE 0 END) as [IN],
    SUM(CASE WHEN OpType = 'OUT' THEN Quantity ELSE 0 END) as [OUT],
    SUM(CASE WHEN OpType = 'OUT' THEN -1 * Quantity ELSE Quantity END) as [FINAL]
FROM Table
GROUP BY Code

更新:在对 JW 웃 回答的评论中,您询问了有关在两个日期之间获取 IN、OUT 和 FINAL 总和的问题。下面是一个更新的查询,它将执行此操作。

DECLARE @InitialSumDate DATETIME = '4/22/2013', @EndDate DATETIME = '4/23/2013'
SELECT 
    @InitialSumDate as [InitialSumDate], @EndDate as [EndDate],
    Code, 
    SUM(CASE WHEN PurchaseDate <= @InitialSumDate AND OpType = 'OUT' THEN -1 * Quantity WHEN PurchaseDate <= @InitialSumDate AND OpType = 'IN' THEN Quantity ELSE 0 END) as [InitialSum],
    SUM(CASE WHEN PurchaseDate >  @InitialSumDate AND PurchaseDate <= @EndDate AND OpType = 'IN'  THEN Quantity ELSE 0 END) as [IN],
    SUM(CASE WHEN PurchaseDate >  @InitialSumDate AND PurchaseDate <= @EndDate AND OpType = 'OUT' THEN Quantity ELSE 0 END) as [OUT],
    SUM(CASE WHEN OpType = 'OUT' AND PurchaseDate <= @EndDate THEN -1 * Quantity WHEN OpType = 'IN' AND PurchaseDate <= @EndDate THEN Quantity ELSE 0 END) as [FINAL]
FROM #Table
GROUP BY Code
于 2013-04-25T14:52:52.433 回答