什么是选择案例的访问SQL等价?(What is the equivalent of Select

2019-08-19 03:12发布

我有一个查询,其中包括命名字段openingbalance佣金 。 我想计算值基于openingbalance,类似这样的佣金 Select Case在Access VBA块:

Select Case OpeningBalance
   Case 0 To 5000
        commission = 20
   Case 5001 To 10000
        commission = 30
   Case 10001 To 20000
        commission = 40
   Case Else
        commission = 50
End Select

但由于Access不允许Select Case在查询中,我怎么能完成我的访问SQL的目标?

Answer 1:

考虑开关功能来替代多个IIf()表达式。 它将从第一表达/值对,其中表达式为真值返回值,并忽略任何剩余的对。 这个概念类似于SELECT ... CASE你引用但其做法是不提供访问SQL。

如果你想显示一个计算的字段作为commission

SELECT
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        ) AS commission
FROM YourTable;

如果你想存储计算值的字段中指定commission

UPDATE YourTable
SET commission =
    Switch(
        OpeningBalance < 5001, 20,
        OpeningBalance < 10001, 30,
        OpeningBalance < 20001, 40,
        OpeningBalance >= 20001, 50
        );

无论哪种方式,看看你是否找到Switch()更容易理解和管理。 多IIf()s可以成为令人难以置信的条件的数量增长。



Answer 2:

您可以使用IIF了类似的结果。

请注意,您可以嵌套IIF语句来处理多个案件。 这里有一个例子: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;


Answer 3:

你可以做如下:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table


文章来源: What is the equivalent of Select Case in Access SQL?