逻辑函数

Power BI 中级 DAX

Carl Rosseel

Curriculum Manager

逻辑函数概览

逻辑函数对表达式求值,返回有关表达式中值或集合的信息。

最常用的逻辑函数:

  • IF()
  • AND(), OR(), NOT()
  • SWITCH()
Power BI 中级 DAX

IF() 是最常用的逻辑函数之一

结构:

  • IF(<logical_test>, <value_if_true>, <value_if_false>)

示例:

  • Performance = IF([Total Sales] >= 50 000, "Target Reached", "Target Not Reached")
Power BI 中级 DAX

IF() 是最常用的逻辑函数之一

结构:

  • IF(<logical_test>, <value_if_true>[, <value_if_false>])

示例:

  • Performance = IF([Total Sales] >= 50 000, "Target Reached", "Target Not Reached")
Name Total Sales
Jenny 48,431
Jane 76,528
Dwayne 24,167
Thomas 52,125
Power BI 中级 DAX

IF() 是最常用的逻辑函数之一

结构:

  • IF(<logical_test>, <value_if_true>[, <value_if_false>])

示例:

  • Performance = IF([Total_Sales] >= 50 000, "Target Reached", "Target Not Reached")
Name Total Sales Performance
Jenny 48,431 Target not Reached
Jane 76,528 Target Reached
Dwayne 24,167 Target Not Reached
Thomas 52,125 Target Reached
Power BI 中级 DAX

AND(), OR() 与 NOT() 运算符

三者均返回 TRUEFALSE

  • AND(<logical1>,<logical2>)
    • 若两条件均为 TRUE,则返回 TRUE
    • 示例:AND(5 < 4, 5 < 6) = AND(FALSE, TRUE) = FALSE
  • OR(<logical1>,<logical2>)
    • 若至少一条件为 TRUE,则返回 TRUE
    • 示例:OR(5 < 4, 5 < 6) = OR(FALSE, TRUE) = TRUE
  • NOT(<logical>)
    • TRUEFALSE 互换
    • 示例:NOT(OR(5 < 4, 5 < 6)) = NOT(TRUE) = FALSE
Power BI 中级 DAX

AND(), OR() 与 NOT() 运算符

AND 可用 && 替代

  • AND(5 < 4, 5 < 6) = 5 < 4 && 5 < 6

OR 可用 || 替代

  • OR(5 < 4, 5 < 6) = 5 < 4 || 5 < 6
Power BI 中级 DAX

SWITCH() 的威力

将表达式与一组取值比较,并返回多个结果表达式之一。

  • SWITCH(<expression>, <value>, <result>[, <value>, <result>] ... [, <else>])
  • 通常优于嵌套的 IF()
    Performance = SWITCH(TRUE, 
    [Total_Sales] < 25 000, "Poor",
    [Total_Sales] < 50 000, "Below expectations",
    [Total_Sales] < 75 000, "Above expectations",
    "Exceptional")
    
Power BI 中级 DAX

SWITCH() 的威力

Performance = SWITCH(TRUE, 
[Total_Sales] < 25 000, "Poor",
[Total_Sales] < 50 000, "Below expectations",
[Total_Sales] < 75 000, "Above expectations",
 "Exceptional")
Name Total Sales
Jenny 48,431
Jane 76,528
Dwayne 24,167
Thomas 52,125
Power BI 中级 DAX

SWITCH() 的威力

Performance = SWITCH(TRUE, 
[Total_Sales] < 25 000, "Poor",
[Total_Sales] < 50 000, "Below expectations",
[Total_Sales] < 75 000, "Above expectations",
 "Exceptional")
Name Total Sales Performance
Jenny 48,431 Below Expectations
Jane 76,528 Exceptional
Dwayne 24,167 Poor
Thomas 52,125 Above expectations
Power BI 中级 DAX

SWITCH() 的威力

DISCOUNT = SWITCH([Clothing Type], 
               "Shoes", 0.15,   
               "Pants", 0.20,
               "Belts", 0.30, 
               "T-shirt", 0.25)
Clothing Type
Shoes
Pants
Belt
T-shirt
Power BI 中级 DAX

SWITCH() 的威力

DISCOUNT = SWITCH([Clothing Type], 
               "Shoes", 0.15,   
               "Pants", 0.20,
               "Belts", 0.30, 
               "T-shirt", 0.25)
Clothing Type Discount
Shoes 15%
Pants 20%
Belt 30%
T-shirt 25%
Power BI 中级 DAX

Let's switch up!

Power BI 中级 DAX

Preparing Video For Download...