如何从同一列SQL中减去两个值

时间:2015-12-18 00:41:28

标签: sql-server

我正在建立一个程序,当给定一个customerID时,它将从帐户类型1(储蓄)余额中减去一个帐户的类型2(信用卡)余额,如果有一个储蓄帐户,则它减去信用额度卡余额。 (前储蓄余额 - 信用卡余额=总余额)

我的表格设置如此

==1

我已经尝试过这样做以获得一些指导,但我发现的一切并没有给我很大的帮助。如果有人可以解释或告诉我我需要做什么,这将是伟大的,这是我的任务的唯一部分,我被困在。

2 个答案:

答案 0 :(得分:2)

您可以按CustomerId进行分组,并获得保存信用余额的总和

select 
    c.CustomerId, 
    SUM(CASE WHEN AccountType = 1 THEN Balance ELSE 0 END) Saving,
    SUM(CASE WHEN AccountType = 2 THEN Balance ELSE 0 END) Credit,
from 
    Customer c
group by 
     c.CustomerId

然后您可以通过以下查询轻松获得总数:

Select 
  CustomerId,
  Saving - Credit
from 
(
  select 
      c.CustomerId, 
      SUM(CASE WHEN AccountType = 1 THEN Balance ELSE 0 END) Saving,
      SUM(CASE WHEN AccountType = 2 THEN Balance ELSE 0 END) Credit,
  from Customer c
  group by c.CustomerId
) cust

答案 1 :(得分:1)

您将表连接到自身,其中连接的每一侧仅包含相应的帐户类型记录:

SELECT coalesce(s.CustomerID, cc.CustomerID) CustomerID
      ,coalesce(s.Number, cc.Number) Number
      coalesce(s.Balance,0) -  coalesce(cc.Balance,0) Balance
FROM (SELECT * FROM [accounts] WHERE AccountType = 2) s
FULL JOIN (SELECT * FROM [accounts] WHERE AccountType = 1) cc on cc.customerID = s.customerID