## Data Analysis Using DAX: Enhancing Customer Engagement Scores

##### Description

This project centers on the application of the DAX ADDCOLUMNS function to augment a dataset with customer engagement scores. Each unit will provide practical insights into specific aspects of the project, guiding you through the steps of setting up your dataset, applying the ADDCOLUMNS function, and analyzing the results. By the end of the project, you will be equipped with hands-on experience in using DAX for data analysis.

The original prompt:

describe for me how to use the ADDCOLUMNS DAX command with a dataset that I want to incorporate aspects of customer engagement scores.

# Introduction to DAX and Customer Engagement Scores

## Overview

DAX (Data Analysis Expressions) is a powerful formula language used in Power BI, Power Pivot, and SQL Server Analysis Services (SSAS) to create custom calculations in reports and data models. This introductory guide will demonstrate practical implementations of using DAX to calculate Customer Engagement Scores (CES).

## Setup Instructions

**Data Preparation:**- Ensure you have a dataset that includes customer interactions, such as purchases, website visits, or customer service interactions. Typical columns might include CustomerID, InteractionType, InteractionDate, and InteractionValue.

**Data Model:**- Import the dataset into Power BI and load it into a new data model.

## Example Dataset

Let's assume the dataset is named `CustomerInteractions`

and has the following columns:

`CustomerID`

`InteractionType`

`InteractionDate`

`InteractionValue`

## DAX Implementations

### 1. Calculate Total Interactions

`Total Interactions = COUNTROWS(CustomerInteractions)`

Explanation: This DAX formula counts the total number of interaction records.

### 2. Calculate Total Interaction Value

`Total Interaction Value = SUM(CustomerInteractions[InteractionValue])`

Explanation: This DAX formula sums up the total value of the interactions.

### 3. Calculate Engagement Score

Let's define an engagement score based on a weighted sum of different interaction types.

First, create a measure for each InteractionType:

`Purchases Score = CALCULATE(SUM(CustomerInteractions[InteractionValue]), CustomerInteractions[InteractionType] = "Purchase")`

`Website Visits Score = CALCULATE(COUNTROWS(CustomerInteractions), CustomerInteractions[InteractionType] = "Website Visit")`

`Customer Service Score = CALCULATE(SUM(CustomerInteractions[InteractionValue]), CustomerInteractions[InteractionType] = "Customer Service")`

Then, combine these to create the Customer Engagement Score (CES):

`Customer Engagement Score = [Purchases Score] * 0.6 + [Website Visits Score] * 0.2 + [Customer Service Score] * 0.2`

Explanation: This formula calculates the overall engagement score by assigning weights to each type of interaction.

### 4. Visualizing CES

To visualize the Customer Engagement Scores:

- Create a
`Table`

or`Matrix`

visual in Power BI. - Add
`CustomerID`

and the`Customer Engagement Score`

measures to the visual. - Optionally, add slicers or filters to analyze engagement by different segments or time periods.

## Conclusion

By utilizing these DAX formulas, you can derive meaningful insights into customer engagement. This setup forms the foundation upon which more sophisticated analytics can be constructed. Ensure you have a clean and well-structured dataset, and use the above DAX implementations to gain valuable metrics on customer interactions.

# Preparing Your Dataset for Analysis using DAX

This section covers the preparation of your dataset for analysis using DAX formulas. We will focus on practical implementations that ensure your dataset is clean, comprehensive, and ready to generate meaningful insights. Our primary objective is to transform raw data into a structured format that can be efficiently analyzed to calculate customer engagement scores.

## Data Cleaning and Transformation

**Removing Duplicates**: Eliminate duplicate records to ensure data consistency.`DISTINCT(TableName)`

Example:

`DISTINCT(Customers)`

**Handling Missing Values**: Replace missing values with an appropriate default to ensure calculations are accurate.`COALESCE([ColumnName], DefaultValue)`

Example:

`COALESCE(Customers[Age], 0)`

**Normalizing Data**: Normalize data to a common scale to ensure consistency across calculations.`SUMX( ADDCOLUMNS(TableName, "NormalizedColumn", DIVIDE([ColumnName] - MIN([ColumnName]), MAX([ColumnName]) - MIN([ColumnName]))) )`

Example:

`SUMX( ADDCOLUMNS(Customers, "Normalized_Engagement", DIVIDE(Customers[EngagementScore] - MIN(Customers[EngagementScore]), MAX(Customers[EngagementScore]) - MIN(Customers[EngagementScore]))) )`

## Data Integration

**Merging Tables**: Merge or join tables to consolidate data from multiple sources.`NATURALINNERJOIN(Table1, Table2)`

Example:

`NATURALINNERJOIN(Customers, Orders)`

**Creating Related Columns**: Create calculated columns to enhance your dataset with additional insights.`ADDCOLUMNS( TableName, "NewColumnName", DAXExpression )`

Example:

`ADDCOLUMNS( Customers, "LifetimeValue", Customers[TotalRevenue] / Customers[YearsActive] )`

## Calculated Columns and Measures

**Calculated Columns**: Define new columns based on existing data to enrich the dataset.`TableName[NewColumnName] = DAXExpression`

Example:

`Customers[EngagementScore] = Customers[PurchaseFrequency] * Customers[AverageSpend]`

**Measures**: Create aggregate calculations that will help analyze your data.`NewMeasure = AggregationFunction(TableName[ColumnName])`

Example:

`TotalRevenue = SUM(Orders[Revenue])`

## Data Filtering

**Filtering Data**: Apply filters to focus the analysis on relevant subsets of the data.

Example:`CALCULATETABLE( TableName, FilterExpression )`

`CALCULATETABLE( Customers, Customers[EngagementScore] >= 50 )`

By executing these DAX formulas, you can clean, transform, integrate, and derive insights from your dataset, ensuring it is well-prepared for analyzing customer engagement scores.

### Conclusion

Follow these steps to ensure your dataset is ready for advanced analysis. Having a well-prepared dataset is critical for generating accurate and meaningful insights with DAX formulas.

### Using ADDCOLUMNS to Calculate Engagement Scores

In this section of your project, we'll use DAX (Data Analysis Expressions) to calculate customer engagement scores by leveraging the `ADDCOLUMNS`

function.

#### 1. Dataset Overview

Assume you have a dataset named `CustomerActivity`

with the following columns:

`CustomerID`

`ActivityType`

`ActivityCount`

We will use `ADDCOLUMNS`

to create a new table, adding a new column called `EngagementScore`

which calculates scores based on activity counts.

#### 2. Example Formula

Here's a DAX formula to calculate the Engagement Scores:

```
EngagementScoresTable =
ADDCOLUMNS (
CustomerActivity,
"EngagementScore",
SWITCH (
[ActivityType],
"PageView", [ActivityCount] * 1,
"NewsletterSubscription", [ActivityCount] * 2,
"Purchase", [ActivityCount] * 5,
0
)
)
```

In this formula:

`CustomerActivity`

is the original table.`"EngagementScore"`

is the new column we are adding.`SWITCH`

function calculates the engagement score based on the type of activity:- Page Views contribute a score of 1 per activity.
- Newsletter Subscriptions contribute a score of 2 per activity.
- Purchases contribute a score of 5 per activity.

#### 3. Explanation

- The
`ADDCOLUMNS`

function creates a new table by adding calculated columns to an existing table. - Each
`CustomerID`

will have an`EngagementScore`

based on their activities.

#### 4. Real-Life Application

To apply this formula in a tool like Power BI:

- Open Power BI Desktop and load your
`CustomerActivity`

dataset. - Open the DAX Editor.
- Paste the
`EngagementScoresTable`

formula into the editor. - This will generate a new table with
`EngagementScore`

calculated for each customer activity.

#### 5. Verification

To verify correctness, you can create visualizations or additional DAX queries to aggregate and analyze the `EngagementScore`

:

```
TotalEngagementScore =
SUMX (
EngagementScoresTable,
[EngagementScore]
)
```

Use the `TotalEngagementScore`

measure in a KPI visual to understand overall customer engagement.

By following these steps, you leverage `ADDCOLUMNS`

to calculate engagement scores effectively using DAX.

# Advanced Techniques in DAX for Data Analysis

## Calculating Weighted Customer Engagement Scores with DAX

This section will demonstrate advanced DAX techniques to calculate weighted customer engagement scores using various DAX functions.

### Step 1: Identifying Engagement Factors and Weights

First, identify key engagement factors and assign weights to them. Let's consider the following example factors:

- Purchase Frequency
- Total Spend
- Customer Reviews
- Website Interaction Duration (Time Spent)

### Step 2: Calculating Individual Scores

Create calculated columns or measures for each factor:

```
-- Calculating Purchase Frequency Score
PurchaseFrequencyScore =
CALCULATE(
COUNT('SalesTable'[OrderID]),
ALLEXCEPT('SalesTable', 'SalesTable'[CustomerID])
)
-- Calculating Total Spend Score
TotalSpendScore =
CALCULATE(
SUM('SalesTable'[TotalAmount]),
ALLEXCEPT('SalesTable', 'SalesTable'[CustomerID])
)
-- Calculating Customer Reviews Score
CustomerReviewScore =
CALCULATE(
AVERAGE('ReviewsTable'[ReviewRating]),
ALLEXCEPT('ReviewsTable', 'ReviewsTable'[CustomerID])
)
-- Calculating Website Interaction Duration Score
InteractionDurationScore =
CALCULATE(
SUM('WebInteractionTable'[DurationMinutes]),
ALLEXCEPT('WebInteractionTable', 'WebInteractionTable'[CustomerID])
)
```

### Step 3: Normalizing the Scores

Normalize the scores to a common scale (0-1) to handle different ranges.

```
-- Normalization Example for Purchase Frequency
NormalizedPurchaseFrequency =
DIVIDE(
'SalesTable'[PurchaseFrequencyScore] - MIN('SalesTable'[PurchaseFrequencyScore]),
MAX('SalesTable'[PurchaseFrequencyScore]) - MIN('SalesTable'[PurchaseFrequencyScore])
)
-- Repeat normalization for other scores
```

### Step 4: Applying Weights and Calculating Final Engagement Score

Assign weights to each factor and calculate the final engagement score:

```
-- Define Weights
VAR WeightPurchaseFrequency = 0.4
VAR WeightTotalSpend = 0.3
VAR WeightCustomerReview = 0.2
VAR WeightInteractionDuration = 0.1
-- Calculate Final Engagement Score
CustomerEngagementScore =
('SalesTable'[NormalizedPurchaseFrequency] * WeightPurchaseFrequency) +
('SalesTable'[NormalizedTotalSpend] * WeightTotalSpend) +
('ReviewsTable'[NormalizedCustomerReview] * WeightCustomerReview) +
('WebInteractionTable'[NormalizedInteractionDuration] * WeightInteractionDuration)
```

### Step 5: Creating a Summary Table

To visualize the engagement scores for all customers, create a summary table:

```
CustomerEngagementSummary =
SUMMARIZE(
'CustomerTable',
'CustomerTable'[CustomerID],
"EngagementScore", [CustomerEngagementScore]
)
```

### Step 6: Advanced Aggregation

Optionally, apply advanced aggregation techniques, such as calculating the average engagement score across different customer segments:

```
AverageEngagementBySegment =
CALCULATETABLE(
SUMMARIZE(
'CustomerSegments',
'CustomerSegments'[Segment],
"AverageEngagementScore", AVERAGE([CustomerEngagementScore])
)
)
```

### Final Thoughts

Using these advanced DAX techniques, you can closely analyze and monitor customer engagement metrics, allowing for more informed business decisions. The steps provided can be readily applied to analyze any engagement-related data within your dataset.

### Interpreting and Visualizing Engagement Scores in DAX

#### Step 1: Create a Calculated Table for Visualization

First, we create a calculated table that aggregates engagement scores for the purpose of visualization.

```
EngagementSummary =
SUMMARIZE(
CustomerTable,
CustomerTable[CustomerID],
"AvgEngagementScore", AVERAGE(CustomerTable[EngagementScore])
)
```

#### Step 2: Define Measures for Dynamic Interpretation

Next, we define measures for interpreting key statistics of engagement scores, such as average, median, and standard deviation.

```
AvgEngagementScore =
AVERAGE(EngagementSummary[AvgEngagementScore])
MedianEngagementScore =
MEDIANX(
EngagementSummary,
EngagementSummary[AvgEngagementScore]
)
StdDevEngagementScore =
STDEVX.P(
EngagementSummary,
EngagementSummary[AvgEngagementScore]
)
HighEngagementCount =
CALCULATE(
COUNTROWS(EngagementSummary),
EngagementSummary[AvgEngagementScore] >= [AvgEngagementScore] + [StdDevEngagementScore]
)
LowEngagementCount =
CALCULATE(
COUNTROWS(EngagementSummary),
EngagementSummary[AvgEngagementScore] <= [AvgEngagementScore] - [StdDevEngagementScore]
)
```

#### Step 3: Create Visualization in Power BI

**Bar Chart to Show Distribution of Engagement Scores**:- Axis:
`CustomerTable[EngagementScore]`

- Values:
`COUNT(CustomerTable[CustomerID])`

- Axis:
**Card Visuals for Key Metrics**:- Card for Average Engagement Score: Display
`AvgEngagementScore`

. - Card for Median Engagement Score: Display
`MedianEngagementScore`

. - Card for Standard Deviation: Display
`StdDevEngagementScore`

.

- Card for Average Engagement Score: Display
**Pie Chart for High vs Low Engagement Segments**:- Values:
`HighEngagementCount`

and`LowEngagementCount`

- Legend:
`High Engagement`

and`Low Engagement`

- Values:
**Trend Line/Line Chart**:- X Axis:
`Date`

(if available in your dataset) - Y Axis:
`AvgEngagementScore`

- X Axis:

#### Final Visualization Description

**Bar Chart**: This will show the distribution of engagement scores, giving a visual representation of the spread and common score ranges.**Card Visuals**: These will summarize key metrics like the average, median, and standard deviation of engagement scores.**Pie Chart**: This will depict the proportion of customers with high vs low engagement scores, helping you quickly identify segments requiring attention.**Trend Line/Line Chart**: This will help in visualizing how the average engagement score changes over time, identifying trends or seasonal variations.

By setting these visuals and using calculated DAX measures, you can effectively interpret and visualize customer engagement scores in your Power BI reports.