sql子查询显示百分比

时间:2017-07-31 14:37:52

标签: sql sql-server

我正在尝试创建一个子查询来显示已接受的事务的结果,并且失败的事务可以指导我如何执行此操作吗? 这是我的疑问:

SELECT ah.MCH_Code,mch.MCH_Name,SUM(isnull(cast(RB.PurchasesPassed as decimal),0))+SUM(isnull(cast(RB.capturesPassed as decimal),0))    
    +SUM(isnull(cast(RB.voidPurchasePassed as decimal),0))+SUM(isnull(cast(RB.creditPassed as decimal),0))
    +SUM(isnull(cast(RB.voidCreditPassed as decimal),0))+SUM(isnull(cast(RB.voidCapturesPassed as decimal),0))
    +SUM(isnull(cast(RB.authPassed as decimal),0))+SUM(isnull(cast(RB.voidAuthPassed as decimal),0)) as 'Passed Transactions',
    SUM(isnull(cast(RB.PurchasesFailed as decimal),0))+SUM(isnull(cast(RB.capturesFailed as decimal),0))
    +SUM(isnull(cast(RB.voidPurchaseFailed as decimal),0))+SUM(isnull(cast(RB.creditFailed as decimal),0))
    +SUM(isnull(cast(RB.voidCreditFailed as decimal),0))+SUM(isnull(cast(RB.voidCapturesFailed as decimal),0))
    +SUM(isnull(cast(RB.authFailed as decimal),0))+SUM(isnull(cast(RB.voidAuthFailed as decimal),0)) as 'Failed Transactions'
  FROM PSP.dbo.MCH_AccountHolder AH 
  LEFT OUTER JOIN [PSP].[dbo].[RECBUILD] RB ON rb.merchantId = ah.MCH_Code
  LEFT OUTER JOIN PSP.dbo.USERS U on ah.UserId = u.USER_ID
  LEFT OUTER JOIN PSP.dbo.MERCHANTS mch  ON mch.MCH_Code = ah.MCH_Code
  where u.USER_ID = '14655' 
  Group by ah.MCH_Code, u.USER_NAME,mch.MCH_Name

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?通过将原始查询转换为CTE(基本上是在主查询结构之外移动的子查询以提高可读性),可以很容易地在其他表达式中使用计算值。这将输出相同的行集,但具有传递的事务占结果中包含的所有事务的百分比。

;With Totals as
(
SELECT ah.MCH_Code,mch.MCH_Name,SUM(isnull(cast(RB.PurchasesPassed as decimal),0))+SUM(isnull(cast(RB.capturesPassed as decimal),0))    
    +SUM(isnull(cast(RB.voidPurchasePassed as decimal),0))+SUM(isnull(cast(RB.creditPassed as decimal),0))
    +SUM(isnull(cast(RB.voidCreditPassed as decimal),0))+SUM(isnull(cast(RB.voidCapturesPassed as decimal),0))
    +SUM(isnull(cast(RB.authPassed as decimal),0))+SUM(isnull(cast(RB.voidAuthPassed as decimal),0)) as 'Passed Transactions',
    SUM(isnull(cast(RB.PurchasesFailed as decimal),0))+SUM(isnull(cast(RB.capturesFailed as decimal),0))
    +SUM(isnull(cast(RB.voidPurchaseFailed as decimal),0))+SUM(isnull(cast(RB.creditFailed as decimal),0))
    +SUM(isnull(cast(RB.voidCreditFailed as decimal),0))+SUM(isnull(cast(RB.voidCapturesFailed as decimal),0))
    +SUM(isnull(cast(RB.authFailed as decimal),0))+SUM(isnull(cast(RB.voidAuthFailed as decimal),0)) as 'Failed Transactions'
  FROM PSP.dbo.MCH_AccountHolder AH 
  LEFT OUTER JOIN [PSP].[dbo].[RECBUILD] RB ON rb.merchantId = ah.MCH_Code
  LEFT OUTER JOIN PSP.dbo.USERS U on ah.UserId = u.USER_ID
  LEFT OUTER JOIN PSP.dbo.MERCHANTS mch  ON mch.MCH_Code = ah.MCH_Code
  where u.USER_ID = '14655' 
  Group by ah.MCH_Code, u.USER_NAME,mch.MCH_Name
 )

SELECT *, Passed Transactions / (Passed Transactions + Failed Transactions) as PctPassed
FROM Totals