MS Access,基于标准的条件求和

时间:2016-02-18 23:23:15

标签: sql ms-access conditional

我在MS Access中创建了一个查询,通过贷款#来汇总调整,如果它们是AA或RA类型。我需要帮助将其转换为SQL,这将在访问中起作用。

SELECT 
    RLI_ManualInterest.[Loan Account Number], 
    SUM(RLI_ManualInterest.[Loan Int Adjustment]) AS [SumOfLoan Int Adjustment],
    RLI_ManualInterest.[GLAcct Interest]
FROM 
    RLI_ManualInterest
WHERE
    (((RLI_ManualInterest.[Adjustment Type]) IN ("AA","RA")))
GROUP BY 
    RLI_ManualInterest.[Loan Account Number];

我需要创建两个字段,一个将包含Int调整的总和,如果调整类型是AA或RA并且将被称为[Loan Int Reaccr Adj Mtd],另一个将包含Int调整的总和,如果调整类型是FX,GL还是FF。

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

使用CASE WHEN来考虑以下条件和表达式,其中大多数RDMS'用于逻辑内联表达式。但偶然的一个例外是MS Access,其ACE / JET SQL方言不携带CASE WHEN。但是使用pass-through queries,您仍然可以在MS Access GUI程序中运行其他本机SQL方言,以与后端数据库(SQL Server,MySQL,Postgre,DB2,Oracle等)进行交互。 )通过ODBC / OLEDB连接。

SELECT RLI_ManualInterest.[Loan Account Number],

       SUM(CASE WHEN RLI_ManualInterest.[Adjustment Type] IN ('AA', 'RA') 
                THEN RLI_ManualInterest.[Loan Int Adjustment]
                ELSE 0 
           END) AS [SumOfLoan Int Adjustment],

       SUM(CASE WHEN RLI_ManualInterest.[Adjustment Type] IN ('FX', 'GL', 'FF') 
                THEN RLI_ManualInterest.[Loan Int Adjustment]
                ELSE 0 
           END) AS [SumOfLoan Int Reaccr Adj Mtd]

FROM RLI_ManualInterest
GROUP BY RLI_ManualInterest.[Loan Account Number];

或者,MS Access中的上述内容使用逻辑IIF()函数(从SQL Server 2012开始为available)。在这两个中,没有其他流行的RDMS使用IIF()

SELECT RLI_ManualInterest.[Loan Account Number],

       SUM(IIF(RLI_ManualInterest.[Adjustment Type] IN ('AA', 'RA'), 
               RLI_ManualInterest.[Loan Int Adjustment],
               0)) AS [SumOfLoan Int Adjustment],

       SUM(IIF(RLI_ManualInterest.[Adjustment Type] IN ('FX', 'GL', 'FF'),
               RLI_ManualInterest.[Loan Int Adjustment],
               0)) AS [SumOfLoan Int Reaccr Adj Mtd]

FROM RLI_ManualInterest
GROUP BY RLI_ManualInterest.[Loan Account Number];