我目前正在尝试获取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
答案 0 :(得分: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]
答案 1 :(得分: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]
答案 2 :(得分:0)
如果TXN_TYPE
总是 +
或-
,您可以尝试这个小技巧:
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'
。虽然它是一个字符串,但由于乘法,它会被隐式转换为数字。