1

我目前正在尝试获取 SQL 表中给定证券的交付总量。如果交易类型为正 (+) [txn 类型],我想计算每一行并将它们相加,或者如果交易类型为负 (-),则从其余结果中删除该总数。我目前可以使用以下代码返回所有行的总和

SELECT     [STOCK REC NO], 
SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0)) AS [TOTAL QUANTITY]
FROM         bla_bla
WHERE     ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]

TXN TYPE    QTY DELIVERED   QTY DUE IN  QTY DUE OUT EVENT DATE
+             1                                      28/11/2005
+             2                                      07/02/2006
-             3                                      22/11/2006
+             20                                     18/04/2011
+             40                                     19/04/2011
4

3 回答 3

1

如果我正确理解您的问题,请这样做

SELECT     [STOCK REC NO], 
SUM(ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DELIVERED], 0) +
    ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DUE IN], 0) - 
    ISNULL(CASE WHEN [TXN TYPE] = '-' THEN -1 ELSE 1 END * [QTY DUE OUT], 0)) 
 AS [TOTAL QUANTITY]
FROM         bla_bla
WHERE     ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]
于 2013-02-13T16:53:48.673 回答
0

如果TXN_TYPE总是要么+or ,你可以-试试这个小技巧:

SELECT     [STOCK REC NO], 
           SUM(
             (TXN_TYPE + '1') * (
             ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0)
             )
           ) AS [TOTAL QUANTITY]
FROM         bla_bla
WHERE     ([EVENT DATE] < '09/26/2012')
GROUP BY [STOCK REC NO]

TXN_TYPE + '1'变为'+1''-1'。虽然它是一个字符串,但由于乘法,它会隐式转换为数字。

于 2013-02-13T17:35:57.063 回答
0
SELECT  [STOCK REC NO],
        CASE TXN_TYPE
            WHEN '+' THEN SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) + ISNULL([QTY DUE OUT], 0))
            ELSE SUM(ISNULL([QTY DELIVERED], 0) + ISNULL([QTY DUE IN], 0) - ISNULL([QTY DUE OUT], 0))
        END AS [TOTAL QUANTITY]
FROM    bla_bla
WHERE   ([EVENT DATE] < '09/26/2012')
GROUP BY
        [STOCK REC NO]
于 2013-02-13T16:55:05.877 回答