我的查询包含名为 openingbalance 和佣金的字段。我想根据 openingbalance 计算佣金的值,类似于Access VBA中的Select Case
块:
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
,我如何在Access SQL中实现我的目标?
答案 0 :(得分:53)
将Switch Function视为多个IIf()
表达式的替代方案。它将从表达式计算结果为True的第一个表达式/值对返回值,并忽略任何剩余的对。该概念类似于您引用的SELECT ... CASE
方法,但在Access 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
会变得令人难以置信。
答案 1 :(得分:5)
您可以使用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;
答案 2 :(得分:1)
你可以在下面做:
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