参考文档:
1
DAX(Data Analysis Expressions)
DAX(Data Analysis Expressions)是 Power BI、Excel 和 SQL Server Analysis Services (SSAS) 中用于创建计算列、度量值和数据分析的公式语言。DAX 主要用于处理和分析数据,以提供深入的商业洞察。以下是 DAX 的一些核心特性和功能:
1. DAX 的核心功能
计算列:
使用 DAX 可以在数据模型中添加计算列,这些列可以基于现有数据列进行计算和生成。例如,你可以创建一个计算列来显示每个销售记录的利润率。
度量值:
DAX 用于定义度量值(又称为聚合值),如总销售额、平均值、最大值等。这些度量值通常用于汇总和分析数据,如计算总收入、平均订单值等。
筛选和上下文:
DAX 支持复杂的筛选和上下文操作,可以在不同的上下文中动态计算值。例如,你可以根据选择的时间范围、地区或其他维度动态计算销售总额。
时间智能功能:
DAX 提供了一系列时间智能函数,帮助用户处理和分析时间数据,如计算同比增长、环比增长、累计总值等。
2. 常见的 DAX 函数和表达式
聚合函数:
SUM(): 计算某列的总和。
AVERAGE(): 计算某列的平均值。
MAX(), MIN(): 计算某列的最大值和最小值。
逻辑函数:
IF(): 根据条件返回不同的值。
SWITCH(): 根据表达式的不同值返回结果。
筛选函数:
FILTER(): 根据指定条件过滤数据。
ALL(), REMOVEFILTERS(): 移除列或表的筛选器。
时间智能函数:
TOTALYTD(), TOTALQTD(), TOTALMTD(): 计算年初至今、季度至今、月初至今的累计值。
DATEADD(), DATESBETWEEN(), DAYS(): 进行日期计算和时间范围筛选。
关系函数:
RELATED(): 从关联表中获取相关数据。
RELATEDTABLE(): 获取与当前行相关的表的数据。
3. DAX 的应用场景
创建动态度量:可以创建动态度量值,如在不同的切片器选择下计算销售总额。
数据分析:用于计算和分析业务指标,如 KPI、销售增长率等。
高级报表功能:为报表和仪表板提供复杂的计算和数据转换,增强数据的可视化效果。
4. 示例
假设你有一个销售数据表,并希望计算每个产品的总销售额和利润率。可以使用以下 DAX 公式:
计算总销售额:
dax
TotalSales = SUM(Sales[SalesAmount])
计算利润率:
dax
ProfitMargin = DIVIDE(SUM(Sales[Profit]), SUM(Sales[SalesAmount]), 0)
总结
DAX 是一个强大且灵活的语言,用于在 Power BI 和其他 Microsoft 工具中进行数据建模和分析。掌握 DAX 可以帮助你创建复杂的计算,提升数据报告和分析的深度。
PowerBI DAX 语法结构
DAX(Data Analysis Expressions)的语法结构主要由以下几个部分组成,类似于 Excel 公式,但在处理数据模型时提供了更多功能和灵活性。以下是 DAX 语法的基本结构和关键元素:
1. 基本结构
DAX 表达式的基本结构可以分为以下几部分:
- 函数:DAX 函数用于执行计算或操作。例如,SUM()、IF() 和 CALCULATE()。
- 参数:函数的输入值或操作对象。例如,SUM(Sales[Amount]) 中的 Sales[Amount] 是参数。
- 运算符:用于执行数学或逻辑运算的符号,例如 +、-、*、/、=。
- 列和表名:在 DAX 公式中引用数据模型中的列和表。
2. DAX 语法元素
a. 函数
DAX 提供了各种内置函数,主要包括:
- 聚合函数:用于计算总和、平均值等。
dax
TotalSales = SUM(Sales[Amount])
- 逻辑函数:用于执行逻辑判断。
dax
IsHighSales = IF(SUM(Sales[Amount]) > 1000, TRUE, FALSE)
- 时间智能函数:用于日期和时间计算。
dax
SalesYTD = TOTALYTD(SUM(Sales[Amount]), Dates[Date])
- 筛选函数:用于创建或修改筛选上下文。
dax
FilteredSales = CALCULATE(SUM(Sales[Amount]), Sales[Category] = "Electronics")
b. 变量
DAX 支持使用变量来简化复杂表达式和提高计算性能。变量使用 VAR 关键字定义,使用 RETURN 关键字返回结果。
dax
SalesAndProfit =
VAR TotalSales = SUM(Sales[Amount])
VAR TotalProfit = SUM(Sales[Profit])
RETURN
TotalSales - TotalProfit
c. 运算符
- 算术运算符:用于数学运算。
+(加)
-(减)
*(乘)
/(除)
- 比较运算符:用于比较值。
=(等于)
<>(不等于)
(大于)
<(小于)
=(大于或等于)
<=(小于或等于)
- 逻辑运算符:用于逻辑操作。
AND(逻辑与)
OR(逻辑或)
NOT(逻辑非)
d. 语法规则
- 列引用:用方括号 [] 包围列名。
dax
Sales[Amount]
- 表引用:通常用表名和列名的组合表示。
dax
SUM(Sales[Amount])
- 函数调用:函数名后跟括号 (),括号内包含参数。
dax
IF(SUM(Sales[Amount]) > 1000, "High", "Low")
3. 示例
- 简单计算:
dax
TotalRevenue = SUM(Sales[Revenue])
- 带有条件的计算:
dax
HighRevenue = IF(SUM(Sales[Revenue]) > 5000, "High", "Low")
- 使用筛选器的计算:
dax
ElectronicsSales = CALCULATE(SUM(Sales[Amount]), Sales[Category] = "Electronics")
- 时间智能计算:
dax
Copy code
SalesLastYear = CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Dates[Date]))
总结
DAX 语法结构灵活且功能强大,可以用来创建复杂的计算和数据分析表达式。通过理解其基本元素和语法规则,你可以有效地在 Power BI 中进行数据建模和分析。
DAX (Data Analysis Expressions)
DAX (Data Analysis Expressions) is a formula language used in Power BI, Excel, and SQL Server Analysis Services (SSAS) to create calculated columns, measures, and perform data analysis. DAX is primarily used to handle and analyze data to provide in-depth business insights. Here are some core features and functionalities of DAX:
1. Core Functions of DAX
Calculated Columns:
DAX allows you to add calculated columns to your data model. These columns can be calculated based on existing data columns. For example, you can create a calculated column to display the profit margin for each sales record.
Measures:
DAX is used to define measures (also known as aggregation values), such as total sales, average values, maximum values, etc. These measures are typically used to aggregate and analyze data, like calculating total revenue, average order value, etc.
Filtering and Context:
DAX supports complex filtering and context operations, allowing you to dynamically calculate values in different contexts. For example, you can calculate total sales dynamically based on selected time ranges, regions, or other dimensions.
Time Intelligence Functions:
DAX provides a range of time intelligence functions to help users handle and analyze time-based data, such as calculating year-over-year growth, month-over-month growth, and running totals.
2. Common DAX Functions and Expressions
Aggregation Functions:
SUM(): Calculates the total of a column.
AVERAGE(): Calculates the average of a column.
MAX(), MIN(): Calculates the maximum and minimum values of a column.
Logical Functions:
IF(): Returns different values based on a condition.
SWITCH(): Returns results based on different values of an expression.
Filtering Functions:
FILTER(): Filters data based on specified conditions.
ALL(), REMOVEFILTERS(): Removes filters from columns or tables.
Time Intelligence Functions:
TOTALYTD(), TOTALQTD(), TOTALMTD(): Calculates year-to-date, quarter-to-date, and month-to-date totals.
DATEADD(), DATESBETWEEN(), DAYS(): Performs date calculations and time range filtering.
Relationship Functions:
RELATED(): Retrieves related data from another table.
RELATEDTABLE(): Retrieves data from a related table.
3. Applications of DAX
Creating Dynamic Measures: Allows you to create dynamic measures, such as calculating total sales based on different slicer selections.
Data Analysis: Used to calculate and analyze business metrics, such as KPIs, sales growth rates, etc.
Advanced Reporting: Provides complex calculations and data transformations for reports and dashboards, enhancing data visualization.
4. Examples
Assuming you have a sales data table and you want to calculate the total sales and profit margin for each product, you can use the following DAX formulas:
Calculate Total Sales:
dax
TotalSales = SUM(Sales[SalesAmount])
Calculate Profit Margin:
dax
Copy code
ProfitMargin = DIVIDE(SUM(Sales[Profit]), SUM(Sales[SalesAmount]), 0)
Summary
DAX is a powerful and flexible language used for data modeling and analysis in Power BI and other Microsoft tools. Mastering DAX can help you create complex calculations and enhance the depth of your data reporting and analysis.
Power BI DAX Syntax Structure
The syntax structure of DAX (Data Analysis Expressions) consists of several key components, similar to Excel formulas but providing more functionality and flexibility for handling data models. Here’s the basic structure and key elements of DAX syntax:
1. Basic Structure
DAX expressions are structured into the following parts:
Functions: DAX functions perform calculations or operations, such as SUM(), IF(), and CALCULATE().
Parameters: The input values or objects for functions. For example, in SUM(Sales[Amount]), Sales[Amount] is a parameter.
Operators: Symbols used for mathematical or logical operations, such as +, -, *, /, =.
Column and Table Names: References to columns and tables in the DAX formula.
2. DAX Syntax Elements
a. Functions
DAX provides various built-in functions, including:
Aggregation Functions: Used to calculate totals, averages, etc.
dax
TotalSales = SUM(Sales[Amount])
Logical Functions: Used to perform logical evaluations.
dax
IsHighSales = IF(SUM(Sales[Amount]) > 1000, TRUE, FALSE)
Time Intelligence Functions: Used for date and time calculations.
dax
SalesYTD = TOTALYTD(SUM(Sales[Amount]), Dates[Date])
Filtering Functions: Used to create or modify filter contexts.
dax
FilteredSales = CALCULATE(SUM(Sales[Amount]), Sales[Category] = "Electronics")
b. Variables
DAX supports using variables to simplify complex expressions and improve calculation performance. Variables are defined using the VAR keyword and the result is returned using the RETURN keyword.
dax
SalesAndProfit =
VAR TotalSales = SUM(Sales[Amount])
VAR TotalProfit = SUM(Sales[Profit])
RETURN
TotalSales - TotalProfit
c. Operators
Arithmetic Operators: Used for mathematical operations.
- (Addition)
- (Subtraction)
- (Multiplication)
/ (Division)
Comparison Operators: Used to compare values.
= (Equals)
<> (Not equal to)
(Greater than)
< (Less than)
= (Greater than or equal to)
<= (Less than or equal to)
Logical Operators: Used for logical operations.
AND (Logical AND)
OR (Logical OR)
NOT (Logical NOT)
d. Syntax Rules
Column References: Enclosed in square brackets [].
dax
Sales[Amount]
Table References: Usually represented by combining table and column names.
dax
SUM(Sales[Amount])
Function Calls: Function names followed by parentheses (), with parameters inside.
dax
IF(SUM(Sales[Amount]) > 1000, "High", "Low")
3. Examples
Simple Calculation:
dax
TotalRevenue = SUM(Sales[Revenue])
Conditional Calculation:
dax
HighRevenue = IF(SUM(Sales[Revenue]) > 5000, "High", "Low")
Calculation with Filter:
dax
ElectronicsSales = CALCULATE(SUM(Sales[Amount]), Sales[Category] = "Electronics")
Time Intelligence Calculation:
dax
SalesLastYear = CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Dates[Date]))
Summary
DAX syntax is flexible and powerful, allowing for the creation of complex calculations and data analysis expressions. By understanding its basic elements and syntax rules, you can effectively perform data modeling and analysis in Power BI.