首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >减借贷方栏目

减借贷方栏目
EN

Stack Overflow用户
提问于 2013-06-27 00:01:09
回答 3查看 806关注 0票数 0

我用sql写了下面的视图

代码语言:javascript
复制
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

结果就是

代码语言:javascript
复制
codea |Description | DEB | CRED |
1      Bank        | 100 | 30   |
2      Cash        | 40  | 70   |
.
.
.

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

代码语言:javascript
复制
codea |Description | DEB | CRED |  NEG | POS |
1      Bank        | 100 | 30   | 70   | 0   |
2      Cash        | 40  | 70   | 0    | 30  |
.
.
.
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-27 00:30:05

尝试如下所示:

代码语言:javascript
复制
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
票数 3
EN

Stack Overflow用户

发布于 2013-06-27 00:27:40

我的想法是使用一个CASE语句来做这件事。

以下是指向sql server案例文档的链接:http://msdn.microsoft.com/en-us/library/ms181765.aspx

我只是猜测您使用的是sql server,因为问题被标记为C#,尽管它应该与mysql,oracle,...也是。

其思想是使用这种情况来知道何时将0放入NEG或POS列,以及将实际结果放在何处。

注意:您真的需要NEG和POS列吗?您不是只想创建一个"result“列吗?

票数 0
EN

Stack Overflow用户

发布于 2013-06-27 00:32:48

对于负数列,您可以使用:

代码语言:javascript
复制
ABS(Min(0, theSubtraction))

对于正数列,您可以使用:

代码语言:javascript
复制
Max(0, theSubtraction)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17325014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档