当前位置: 首页 > news >正文

PowerBI_Chapter6:DAX

`

文章目录

  • 前言
  • 一、DAX Overview / DAX 概述
    • (一)What is DAX? / 什么是DAX?
      • 1. Definition 定义
      • 2. Data Types 数据类型
      • 3. Key Capabilities 核心能力
    • (二)Why Learn DAX? / 为什么要学DAX?
  • 二、DAX Syntax / DAX 语法
    • (一)Formula Structure / 公式结构
      • 1. Example 示例
      • 2. Elements 组成元素
      • 3. Plain Language Reading 通俗解读
  • 三、Types of DAX Expressions / DAX 表达式类型
    • (一)Calculated Columns / 计算列
    • (二)Measures / 度量值
    • (三)Calculated Tables / 计算表
    • (四)Row-Level Security Expressions / 行级安全表达式
  • 四、Common DAX Functions by Category / 常用DAX函数分类
    • (一)Aggregation Functions / 聚合函数
    • (二)Logical Functions / 逻辑函数
    • (三)Text Functions / 文本函数
    • (四)Date and Time Functions / 日期与时间函数
    • (五)Filter Functions / 筛选函数
    • (六)Mathematical Functions / 数学函数
    • (七)Information Functions / 信息函数
    • (八)Time Intelligence Functions / 时间智能函数
  • 五、Calculated Columns in Detail / 计算列详解
    • (一)Mathematical Functions / 数学函数示例
    • (二)Date Functions / 日期函数示例
    • (三)Text Functions / 文本函数示例
    • (四)Logical Functions / 逻辑函数示例
    • (五)Information Functions / 信息函数示例
  • 六、DAX Measures / DAX 度量值
    • (一)Definition 定义
    • (二)Types of Measures / 度量类型
      • 1. Implicit Measures / 隐式度量
      • 2. Explicit Measures / 显式度量
    • (三)Aggregation Functions Used in Measures / 度量中常用的聚合函数
  • 七、CALCULATE Function / CALCULATE 函数
    • (一)Purpose 作用
    • (二)Adding Filters with CALCULATE / 使用CALCULATE添加筛选
    • (三)Adding Filters with FILTER() / 使用FILTER()添加筛选
    • (四)Removing Filters / 移除筛选
    • (五)Updating Filters / 更新筛选
  • 八、Time Intelligence Functions / 时间智能函数
    • (一)Prerequisites / 前提条件
    • (二)Key Functions / 关键函数
      • 1. DATESYTD() / 年初至今日期表
      • 2. DATESMTD() / 月初至今日期表
      • 3. TOTALYTD() / 年初至今总计
      • 4. DATESINPERIOD() / 指定周期日期表
      • 5. SAMEPERIODLASTYEAR() / 去年同期日期表
      • 6. PREVIOUSYEAR() / 前一年
  • 九、Replace Implicit Measures with Explicit Measures / 用显式度量替换隐式度量
    • (一)Why Replace? / 为什么要替换?
    • (二)Best Practice / 最佳实践
  • 十、Characteristics of Measures / 度量的特性
    • (一)Additive Measures / 可加性度量
    • (二)Semi-Additive Measures / 半可加性度量
    • (三)Non-Additive Measures / 不可加性度量
  • 十一、Quick Measures / 快速度量
  • 总结 / Summary
    • 核心考点(Top 5)

前言

本文是Power BI Desktop第六章“DAX(数据分析表达式)”的期末复习笔记,结合教材与考试重点整理。内容涵盖:DAX基础语法、计算列、度量值、计算表、常用函数(聚合、逻辑、文本、日期、信息)、CALCULATE筛选操纵、时间智能函数、度量特性及隐式替换。


一、DAX Overview / DAX 概述

(一)What is DAX? / 什么是DAX?

1. Definition 定义

  • DAX (Data Analysis Expressions)is aformula expression language used in Power BI, Excel, and other BI tools for creating customcalculations and aggregations on data models.
    DAX(数据分析表达式)是一种公式表达式语言,用于在Power BI、Excel等BI工具中对数据模型创建自定义计算和聚合。

  • DAX is also known asfunction language, where the full code is kept inside a function.a collection of functions
    DAX也被称为函数语言,完整代码都放在函数内部。

2. Data Types 数据类型

  • Numeric: integers, currency, decimals. / 数值型:整数、货币、小数。
  • Other: string, binary object. / 其他:字符串、二进制对象。

3. Key Capabilities 核心能力

  • Perform Calculations: Use built-in functions for math, stats, logic, and text operations. / 执行计算:使用内置函数进行数学、统计、逻辑和文本操作。
  • Aggregate Data: Use SUM, AVERAGE, COUNT, etc., including running totals and moving averages. / 聚合数据:使用SUM、AVERAGE、COUNT等,包括运行总和和移动平均。
  • Time Intelligence: Year-over-year, cumulative totals, date-based filtering. / 时间智能:同比、累计总计、基于日期的筛选。
  • Create Relationships: Work across multiple tables. / 创建关系:跨多个表计算。
  • Filter Context: Dynamic analysis based on user selections. / 筛选上下文:基于用户选择的动态分析。

(二)Why Learn DAX? / 为什么要学DAX?

  • Extractactionable insightsfrom data. / 从数据中提取可操作的见解
  • Solve business problems affecting decision-making and bottom line. / 解决影响决策和利润的业务问题。
  • Create sophisticated calculations, dynamic reports, and advanced capabilities (time intelligence, conditional logic). / 创建复杂计算、动态报表和高级功能(时间智能、条件逻辑)。

二、DAX Syntax / DAX 语法

(一)Formula Structure / 公式结构

1. Example 示例

T o t a l S a l e s = S U M ( S a l e s [ S a l e s A m o u n t ] ) Total Sales = SUM(Sales[SalesAmount])TotalSales=SUM(Sales[SalesAmount])

2. Elements 组成元素

  • Measure Name:Total Sales– name that appears in report. / 度量名称。
  • Equals sign (=): Indicates beginning of formula. / 等号,表示公式开始。
  • DAX Function:SUM– defines the calculation. / DAX函数,定义计算。
  • Parentheses (): Surround arguments. / 括号,包围参数。
  • Table Reference:Sales– table containing data. / 表引用。
  • Column Reference:[SalesAmount]– column to aggregate. / 列引用。

3. Plain Language Reading 通俗解读

“For the measure namedTotal Sales, calculate theSUMof values in the[SalesAmount]column in the Sales table.”
“对于名为总销售额的度量,计算Sales表中[SalesAmount]列的SUM。”


三、Types of DAX Expressions / DAX 表达式类型

(一)Calculated Columns / 计算列

  • Row-by-rowcomputation, stored in the table. / 逐行计算,存储在表中。
  • Use cases: Filters/slicers, intermediate steps, specific conditions (e.g., categorizing sales as “High/Medium/Low”). / 用途:筛选/切片器、中间步骤、特定条件判断。
  • Example:Status = IF(Sales[Total_Sales] > 1000, "Good", "Bad")

(二)Measures / 度量值

  • Dynamiccalculations evaluated on the fly based on filter context. Not stored. / 动态计算,基于筛选上下文实时评估,不存储。
  • Use cases: Aggregations like totals, averages, percentages. / 用途:求和、平均、百分比等聚合。
  • Example:Total Sales = SUM(Sales[SalesAmount])

(三)Calculated Tables / 计算表

  • DAX expressions that returnentire tables, used for modeling or creating subsets. / 返回整个表的DAX表达式,用于建模或创建子集。
  • Example:TopSales = FILTER(Sales, Sales[SalesAmount] > 1000)

(四)Row-Level Security Expressions / 行级安全表达式

  • Define filters in security roles to restrict data access. / 在安全角色中定义筛选器以限制数据访问。
  • Example:[Region] = "North America"

对比维度DAX Functions(DAX函数)DAX Expressions(DAX表达式)
定义预定义的操作或计算单元,是公式的基本构件。由函数、运算符、常量及引用组合而成的完整计算公式。
作用执行特定动作(如求和、判断、日期计算等)。定义如何计算、返回或转换数据,产生最终结果。
组成单一功能块(如SUMIFCALCULATE)。可包含多个函数、运算符、列引用和常量(如SUM(Sales[Amount]) * 1.1)。
返回类型通常返回标量值或表(取决于函数类型)。可返回标量、表或布尔值,取决于表达式用途(度量、计算列、计算表等)。
使用场景作为表达式的一部分被调用,不能独立存在。可独立创建为度量、计算列、计算表或行级安全规则。
示例SUMAVERAGEIFCALCULATEDATESYTDTotal Sales = SUM(Sales[SalesAmount])(度量表达式);
Status = IF(Sales[Amount] > 1000, "High", "Low")(计算列表达式)。
是否可单独使用否,必须嵌入表达式中。是,可独立保存在模型中(如度量、计算列)。
核心关系函数是表达式的“原材料”,表达式是函数的“容器”和“调用者”。表达式通过调用一个或多个函数,并搭配运算符和引用,完成具体业务逻辑。

四、Common DAX Functions by Category / 常用DAX函数分类

(一)Aggregation Functions / 聚合函数

  • SUM(),AVERAGE(),MIN(),MAX(),COUNT(),DISTINCTCOUNT(),COUNTROWS()

(二)Logical Functions / 逻辑函数

  • IF(),AND(),OR(),SWITCH()

(三)Text Functions / 文本函数

  • CONCATENATE(),LEFT(),RIGHT(),LEN(),UPPER(),LOWER(),REPLACE(),SUBSTITUTE(),SEARCH(),FIND(),FORMAT(),TRIM(),CLEAN()

(四)Date and Time Functions / 日期与时间函数

  • YEAR(),MONTH(),DAY(),TODAY(),NOW(),DATEDIFF(),DATE()

(五)Filter Functions / 筛选函数

  • CALCULATE(),FILTER(),ALL(),ALLEXCEPT()

(六)Mathematical Functions / 数学函数

  • ROUND(),CEILING(),FLOOR(),MOD(),POWER(),DIVIDE()

(七)Information Functions / 信息函数

  • ISBLANK(),ISERROR(),ERROR(),ISNUMBER(),ISTEXT(),ISNONTEXT(),ISEVEN(),ISODD()

(八)Time Intelligence Functions / 时间智能函数

  • TOTALYTD(),DATESYTD(),DATESMTD(),DATESINPERIOD(),SAMEPERIODLASTYEAR(),PREVIOUSYEAR()

五、Calculated Columns in Detail / 计算列详解

(一)Mathematical Functions / 数学函数示例

  • Sales = Sales[SellingPrice] * Sales[Quantity]
  • Avg_Sales = DIVIDE(Sales[Sales], Sales[SellingPrice])
  • Power = POWER(Sales[Quantity], 2)

(二)Date Functions / 日期函数示例

  • Extract components:Year = Sales[SaleDate].[Year],Month = Sales[SaleDate].[Month],Day = Sales[SaleDate].[Day]
  • Current date:Current_date = TODAY(),CurrentDateTime = NOW()
  • Difference:DaysOpen = DATEDIFF(Customer[StartDate], Customer[EndDate], DAY)
  • Age:Age = DATEDIFF(Sales[SaleDate], TODAY(), DAY)
  • Create date:Custom_Date = DATE(2025,3,1)
  • Format:Custom_Date = FORMAT(DATE(2025,3,1), "yyyy-mm-dd")

(三)Text Functions / 文本函数示例

  • Concatenate:Merge = CONCATENATE('product'[Product], 'product'[Category])orMerge = 'product'[Product] & " | " & 'product'[Category]
  • Case:Lower = LOWER('product'[Product]),Upper = UPPER('product'[Product])
  • Length:len = LEN('product'[Product])
  • Extract:short_name = LEFT('product'[Product], 3),RIGHT(...)
  • Search:Search = IFERROR(SEARCH("Oak", Customer[Address]), BLANK())
  • Replace:NewName = REPLACE(Customer[Name], 1, 4, "Mr.")
  • Substitute:NewCol = SUBSTITUTE(Table[description], "laptop", "tablet")

(四)Logical Functions / 逻辑函数示例

  • Simple IF:Status = IF(Sales[Sales] > 1000, "Good", "Bad")
  • AND:Flag = IF(Sales[SellingPrice] > 1000 && Sales[Quantity] > 2, "Valid", "Invalid")
  • OR:Status = IF(Sales[Sales] || Sales[SellingPrice] > 1000, "Good", "Bad")
  • SWITCH (multiple conditions):
    Grade = SWITCH(TRUE(), Sales[Sales] >= 3000, "High Profit", Sales[Sales] >= 2000, "Profit", Sales[Sales] >= 1000, "No Profit", "Loss" )

(五)Information Functions / 信息函数示例

  • ISBLANK(Customer[Name])
  • ISNUMBER(Customer[CustomerID])
  • ISTEXT(Customer[CustomerID])
  • ERROR(Customer[Address])

六、DAX Measures / DAX 度量值

(一)Definition 定义

  • AMeasureis acalculated fieldwritten in DAX that performs calculations dynamically based on user interactions (filters, slicers, visuals).
    度量是用DAX编写的计算字段,根据用户交互(筛选器、切片器、视觉对象)动态执行计算。

  • Measuresdo not store data; they calculate resultson the fly.
    度量不存储数据,而是即时计算结果。

(二)Types of Measures / 度量类型

1. Implicit Measures / 隐式度量

  • Automatically created by Power BI when you drag a numeric column into a visual. / 将数字列拖入视觉对象时,Power BI自动创建。
  • Limitations: No custom logic, not reusable, not visible in Fields pane. / 局限:无自定义逻辑,不可重用,不在字段窗格显示。

2. Explicit Measures / 显式度量

  • Manually created using DAX formula bar. / 使用DAX公式栏手动创建。
  • Advantages: Reusable, full control over logic and formatting, visible with calculator icon. / 优点:可重用,完全控制逻辑和格式,带计算器图标显示。

(三)Aggregation Functions Used in Measures / 度量中常用的聚合函数

  • SumOfSales = SUM(Sales[Sales])
  • Average = AVERAGE(Sales[Sales])
  • Total_count = COUNT(Sales[SaleID])
  • Dis_count = DISTINCTCOUNT(Sales[ProductID])

七、CALCULATE Function / CALCULATE 函数

(一)Purpose 作用

  • CALCULATE()modifies thefilter contextof a calculation. It allows you to add, remove, or override filters dynamically.
    CALCULATE()用于修改计算的筛选上下文,允许动态添加、删除或覆盖筛选器。

(二)Adding Filters with CALCULATE / 使用CALCULATE添加筛选

  • Single filter:
    Laptop_Sale = CALCULATE([SumOfSales], Sales[ProductID] = "P001")
  • Multiple values (IN):
    Sales_Laptop_Phone = CALCULATE([SumOfSales], Sales[ProductID] IN {"P001", "P002"})
  • Multiple columns (AND):
    MotorCycle Sales 2023 = CALCULATE([TotalOfSales], products[productLine] = "Motorcycles", orders[year] = 2023)

(三)Adding Filters with FILTER() / 使用FILTER()添加筛选

  • FILTER()returns a table of filtered data and is used inside CALCULATE.
    JanSales = CALCULATE([SumOfSales], FILTER(sales, Sales[Month] = "January"))
  • Multiple conditions:
    JanSalesmorethan1000 = CALCULATE([Total Sales], FILTER(sales, Sales[salesprice] > 1000 && Sales[Month] = "January"))

(四)Removing Filters / 移除筛选

  • Remove filter on asingle column:
    ProfitAllproducts = CALCULATE([Laptop_mobile], ALL(Sales[ProductID]))
  • Remove all filters from awhole table:
    Profit All Sales Territories = CALCULATE([Total Profit], ALL(Sales))

(五)Updating Filters / 更新筛选

  • Abbreviated filter:City[SalesTerritory] = "New England"
    Equivalent to:FILTER(ALL(City[SalesTerritory]), City[SalesTerritory] = "New England")

八、Time Intelligence Functions / 时间智能函数

(一)Prerequisites / 前提条件

  • Need aDate tablewith unique date values, marked as a date table. / 需要一个具有唯一日期值的日期表,并标记为日期表。
  • Most time intelligence functions returntables of datesused as filters in CALCULATE. / 大多数时间智能函数返回日期表,用作CALCULATE中的筛选器。

(二)Key Functions / 关键函数

1. DATESYTD() / 年初至今日期表

  • Returns all dates from Jan 1st to the current date in context. / 返回从1月1日到当前上下文中日期的所有日期。
  • DatesYTD = CALCULATE([SumOfSales], DATESYTD(Sales[SaleDate]))

2. DATESMTD() / 月初至今日期表

  • Returns all dates from the start of the month to the current date. / 返回从月初到当前日期的所有日期。
  • DatesMTD = CALCULATE([SumOfSales], DATESMTD(Sales[SaleDate]))

3. TOTALYTD() / 年初至今总计

  • Directly calculates YTD total without CALCULATE wrapper. / 直接计算年初至今总计,无需CALCULATE包裹。
  • SalesYTD = TOTALYTD([SumOfSales], Sales[SaleDate])

4. DATESINPERIOD() / 指定周期日期表

  • Returns a table of dates for a specified period before/after a given date. / 返回给定日期前后指定时间段的日期表。
  • Last10days = CALCULATE([SumOfSales], DATESINPERIOD(Sales[SaleDate], "04-10-2025", -10, DAY))

5. SAMEPERIODLASTYEAR() / 去年同期日期表

  • Returns dates from the same period in the previous year. / 返回去年同期的日期。
  • Sales LY = CALCULATE(SUM(Sales[SellingPrice]), SAMEPERIODLASTYEAR(Sales[SaleDate]))

6. PREVIOUSYEAR() / 前一年

  • Returns all dates of the previous year based on current context. / 基于当前上下文返回前一年的所有日期。
  • PreviousYr = CALCULATE([SumOfSales], PREVIOUSYEAR(Sales[SaleDate]))

九、Replace Implicit Measures with Explicit Measures / 用显式度量替换隐式度量

(一)Why Replace? / 为什么要替换?

  • Implicit measureslack control(no custom filtering, formatting, or logic). / 隐式度量缺乏控制
  • Theycan’t be reusedacross visuals. / 不可跨视觉对象重用
  • They’renot visiblein the Fields pane. / 在字段窗格中不可见
  • Explicit measures make your modelcleaner,more powerful, andmaintainable. / 显式度量使模型更干净强大可维护

(二)Best Practice / 最佳实践

  • Always create explicit measures for any calculation that will be used in multiple visuals or needs complex logic. / 任何将在多个视觉对象中使用或需要复杂逻辑的计算,都应创建显式度量。

十、Characteristics of Measures / 度量的特性

(一)Additive Measures / 可加性度量

  • Can be summed acrossall dimensions(time, geography, product, etc.). / 可跨所有维度(时间、地理、产品等)求和。
  • Examples: Sales Amount, Units Sold, Revenue, Cost. / 示例:销售额、销量、收入、成本。

(二)Semi-Additive Measures / 半可加性度量

  • Can be added acrosssome dimensions(e.g., region, product) butnot across time. / 可跨某些维度(如地区、产品)求和,但不能跨时间
  • Examples: Inventory (take last value), Bank Balance, Account Balance. / 示例:库存(取最后值)、银行余额、账户余额。

(三)Non-Additive Measures / 不可加性度量

  • Cannot be added across any dimension; must use special aggregations like average, ratio, or distinct count. /不能跨任何维度求和,必须使用平均、比率、非重复计数等特殊聚合。
  • Examples: Profit Margin (%), Conversion Rate, Average Price, Customer Satisfaction Score. / 示例:利润率(%)、转化率、平均价格、客户满意度评分。

十一、Quick Measures / 快速度量

  • In Power BI,Quick Measuresare predefined DAX calculations that allow you to easily create common and complex measureswithout manually writing DAX code.
    在Power BI中,快速度量是预定义的DAX计算,允许你无需手动编写DAX代码即可轻松创建常见和复杂的度量。

  • They are a great starting point for learning DAX syntax. / 它们是学习DAX语法的良好起点。


总结 / Summary

核心考点(Top 5)

  1. DAX 三大表达式类型– 计算列(逐行存储)、度量(动态即时)、计算表(返回表)。
  2. CALCULATE 核心用法– 修改筛选上下文(添加/删除/覆盖),结合FILTER、ALL等函数。
  3. 时间智能函数– TOTALYTD, DATESYTD, DATESMTD, DATESINPERIOD, SAMEPERIODLASTYEAR(需日期表)。
  4. 度量特性– 可加性(全维度求和)、半可加性(不跨时间)、不可加性(用平均/比率)。
  5. 显式 vs 隐式度量– 显式可重用、可控;隐式快捷但局限。
http://www.gsyq.cn/news/1584320.html

相关文章:

  • 基于Nessus的API安全扫描实战:从通用扫描到定制化漏洞检测
  • WD5081高压降压转换器详解:90V输入、1A输出、SOT23-6小封装
  • 制作5G新时代科学知识页面
  • Android Studio项目可直接集成的纯Java/Kotlin双摇杆控件,横屏游戏操控专用
  • CVE-2017-17733漏洞复现:从PHP eval()到远程命令执行实战
  • while 与 do-while 的底层逻辑对决-算平均数
  • 【MATLAB】山地复杂地形无人机航路规划仿真
  • GPT-5.6 Agent安全实战:提示注入攻防SOP与企业权限治理手册
  • 丹东黄金白银回收铂金旧金回收无套路门店 TOP 榜单 实地测评资料整理
  • 微信QQ消息防撤回工具原理与部署指南:钩子技术与内存拦截解析
  • 基于 C++ 实现的(控制台)考试系统
  • Spring AI 2.x 深度技术解析:从架构重构到企业级落地
  • 先导02:SECS\-I 串口 \+ HSMS 以太网完整通信底层原理
  • Meta 员工跟踪计划因安全漏洞暂停,内部数据收集引隐私担忧
  • 抚顺黄金白银回收铂金旧金回收无套路门店 TOP 榜单 实地测评资料整理
  • 先导01:SEMI 行业标准体系总览 E4/E5/E37/E87/E40/E94 完整拆解
  • UNiTY疑难杂症
  • Google研究:对话式医疗系统AMIE升级,管理推理能力不劣于人类医生!
  • Python:第11天:异常处理 —— 让程序不轻易崩溃
  • 2026 年企业级大模型API聚合网关选型实录:十款主流平台技术横评与场景匹配
  • 三年累亏超3亿、现金流持续为负,思必驰凭什么再闯科创板?
  • 告别GitHub英文困扰:5分钟实现中文界面的完整指南
  • AI教材写作必备:低查重AI工具,助你快速打造精品教材!
  • 6个本科绿牌专业薪资大揭秘,3S专业就业差距在哪?
  • Kubernetes 日志快速定位
  • 手把手教你从0到1搭建一个AI Agent(智能体)
  • 2026气液增压器品牌格局重塑:国际、台系与国产的三方博弈
  • 洛雪音乐六音音源终极修复指南:5分钟恢复完整音乐体验
  • 知名的GPRC5D(Detergent)膜蛋白厂家名声
  • 如何快速上手AlienFX Tools:Alienware灯光、风扇和电源控制的终极指南