<!-- https://learnsql.cpetoday.com/functions/dax/sumx -->
# SUMX

Language: DAX
Category: Aggregation
Syntax: SUMX(<table>, <expression>)
Summary: Evaluates an expression on each row of a table, then adds the results.
Returns: A number (a scalar). BLANK when the expression has no values to add.
Level: Intermediate
Related: SUM, AVERAGEX, MAXX, CALCULATE, RELATED, COUNTX

## What it does
SUMX walks down a table one row at a time, works out the expression on that row, and adds up all the results. It is the tool for totals that need a calculation on each line, such as quantity times unit cost. The filter context still applies, so only the rows that survive the slicers and filters are visited.

## Syntax and arguments
- table: the table to walk, such as `Sales` or a filtered table such as `FILTER(Sales, ...)`.
- expression: the calculation for each row. It can use columns of the table and, with RELATED, columns from a table on the one side of a relationship.

## Example
The operations team wants standard cost, which is the quantity sold times the unit cost held on the product list, not the cost recorded on each sale.

```dax
Standard Cost =
SUMX(
    Sales,
    Sales[SalesQuantity] * RELATED(Product[UnitCost])
)
```

For each sales line, RELATED fetches the unit cost of that product. SUMX multiplies it by the quantity and adds the lines together. Compare this with the recorded cost in `Sales[TotalCost]` to see whether cost is booked at the standard rate.

## Example: a second, different use
Profit earned only on lines that made money, for a review of the profitable part of the business:

```dax
Profitable Line Margin =
SUMX(
    FILTER(Sales, Sales[SalesAmount] > Sales[TotalCost]),
    Sales[SalesAmount] - Sales[TotalCost]
)
```

FILTER keeps only the lines with a positive margin, then SUMX adds the margin of those lines. Loss lines are left out entirely, not netted off.

## Things to watch
- SUMX is slower than SUM because it visits every row. When a column already holds the answer, use SUM.
- Columns of the current row are read directly. Columns in a related table need RELATED, otherwise the formula fails or returns an error.
- A measure used inside SUMX is evaluated once per row. The result is correct, but large tables can be slow. Keep the row formula as simple as you can.
- Blank results are skipped. A row with a blank expression adds nothing.
- SUMX over the whole fact table is rarely needed for totals that a plain SUM already handles. Reach for it only when a per row calculation is part of the business rule.

## In business terms
SUMX is how finance builds extended amounts: quantity times price for invoice totals, hours times rate for labor cost, units times standard cost for inventory valuation, and any margin calculated line by line before it is added up.
