0

我在sql中写了以下视图

SELECT     TOP (100) PERCENT Accounting.TopicA.CodeA, SUM(Accounting.DocumentDetail.Debit) AS DEB, SUM(Accounting.DocumentDetail.Credit) AS CRED, 
                      Accounting.TopicA.Description
FROM         Accounting.TopicA INNER JOIN
                      Accounting.DocumentDetail ON Accounting.TopicA.CodeA = SUBSTRING(Accounting.DocumentDetail.Topic, 1, 2)
GROUP BY Accounting.TopicA.CodeA, Accounting.TopicA.Description
ORDER BY Accounting.TopicA.CodeA

结果是

codea |Description | DEB | CRED |
1      Bank        | 100 | 30   |
2      Cash        | 40  | 70   |
.
.
.

现在我需要再添加两列来减去 DEB 和 CRED,比如当减法为正时,然后将结果放在 POS 列中,否则 NEG 列如下所示

codea |Description | DEB | CRED |  NEG | POS |
1      Bank        | 100 | 30   | 70   | 0   |
2      Cash        | 40  | 70   | 0    | 30  |
.
.
.
4

3 回答 3

3

尝试这样的事情:

SELECT TOP (100) PERCENT Accounting.TopicA.CodeA,
SUM(Accounting.DocumentDetail.Debit) AS DEB,
SUM(Accounting.DocumentDetail.Credit) AS CRED,
CASE WHEN SUM(Accounting.DocumentDetail.Credit) - SUM(Accounting.DocumentDetail.Debit) < 0
THEN SUM(Accounting.DocumentDetail.Debit) - SUM(Accounting.DocumentDetail.Credit)
ELSE 0 END AS NEG,
CASE WHEN SUM(Accounting.DocumentDetail.Credit) - SUM(Accounting.DocumentDetail.Debit) > 0
THEN SUM(Accounting.DocumentDetail.Credit) - SUM(Accounting.DocumentDetail.Debit)
ELSE 0 AS POS,
Accounting.TopicA.Description
FROM Accounting.TopicA 
INNER JOIN Accounting.DocumentDetail 
ON Accounting.TopicA.CodeA = SUBSTRING(Accounting.DocumentDetail.Topic, 1, 2)
GROUP BY Accounting.TopicA.CodeA, Accounting.TopicA.Description
ORDER BY Accounting.TopicA.CodeA
于 2013-06-26T16:30:05.347 回答
0

对于负列,您可以使用:

ABS(Min(0, theSubtraction))

对于正列,您可以使用:

Max(0, theSubtraction)
于 2013-06-26T16:32:48.173 回答
0

我有想法使用 CASE 语句来做到这一点。

这是 sql server 的 CASE 文档的链接:http: //msdn.microsoft.com/en-us/library/ms181765.aspx
我只是猜测您正在使用 sql server,因为问题标记为 C#,尽管它应该是也兼容 mysql、oracle 等。

想法是使用此 CASE 来了解何时将 0 放入 NEG 或 POS 列,以及将实际结果放入何处。

注意:你真的必须有 NEG 和 POS 列吗?您不只是想创建一个“结果”列吗?

于 2013-06-26T16:27:40.067 回答