扣除借方和贷方列

时间:2013-06-26 16:01:09

标签: c# sql tsql

我在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  |
.
.
.

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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专栏吗?你不想只想创建一个“结果”列吗?

答案 2 :(得分:0)

对于负列,您可以使用:

ABS(Min(0, theSubtraction))

您可以使用的正列:

Max(0, theSubtraction)