如何计算SQL Server中的正余额和负余额为正数?

时间:2017-09-08 21:41:48

标签: sql-server join

我编写了代码,以便为我提供已置于特定保留状态的帐户的CurrentBalance。

问题是:

  • 当他们是PostPaid账户时,余额为正数。
  • 当它们是预付帐户时,欠款余额为负数。

我的代码如下(不给我任何预付帐户):

SELECT A.[AccountId]
      ,AccountNumbe]
      ,AccountStatusId
      ,AccountTypeId
      ,CASE WHEN P.PlanCode = 'P0100'
            THEN 'PrePaid'
            WHEN P.PlanCode = 'P0200'
            THEN 'PostPaid'
       END PlanType
      ,CASE WHEN P.PlanCode = 'P0100'
            THEN ABS([CurrentBalance])
        WHEN P.PlanCode = 'P0200'
            THEN [CurrentBalance]
       END CurrentBalance
      ,HoldStatusId
      ,D.Last_Change

  FROM [Account] A

  INNER JOIN  ( 
               SELECT AccountId
             ,MAX(Created) Last_Change
        FROM HoldHistory
        WHERE ToHoldStatusId IN (1,2,11)               
        GROUP BY AccountId
        ) D
        ON A.AccountID = D.AccountId

  INNER JOIN AccountPlan P ON A.AccountId = P.AccountId

  WHERE HoldStatusId IN (1,2,11)
    AND AccountStatusId IN (1,2)
    AND DATEDIFF (DAY, D.Last_Change, GETDATE()) > 180
    AND [CurrentBalance] > 25

  ORDER BY PlanType --CurrentBalance DESC, AccountNumber


--

但是当我运行此查询时,我只获得所有PostPaid帐户。我没有得到任何预付帐户。

如果我这样做:

AND ABS([CurrentBalance]) > 25  --instead of AND [CurrentBalance] > 25
然后这可能行不通,因为有些PostPaid账户支付的金额超过他们应付下个月的账单。这使他们处于负平衡状态。

有什么建议吗?我的代码中的错误在哪里?

1 个答案:

答案 0 :(得分:0)

PrePaid为负数,PostPaid为正数?

WHERE 
(
      (P.PlanCode = 'P0100' AND CurrentBalance < 25)
OR    (P.PlanCode = 'P0200' AND CurrentBalance > 25)
)