Hi everyone,
I'm trying to create a running sum measure in DAX that changes dynamically based on the applied filters. The running sum should accumulate values according to the rank of each row. I've already created separate tables, and they work as expected. However, when I attempt to implement this using a measure with virtual tables, it doesn't produce the desired result.
Here's the code I'm working with. Each part seems to work independently (e.g., ranking and filtering), but as a combined measure, it fails to return the correct running sum per rank.
Running_sum_measure =
VAR tbl_1 =
ADDCOLUMNS(
FILTER(ALL(sales_table[CodigoArticulo]),[CQ1]>0)
,"porc"
,[PorcentajeParticipacionCQ1]
)
VAR tbl_1_sorted =
ADDCOLUMNS(
tbl_1,
"Rank",
RANKX(
tbl_1,
[porc] + RAND() * 0.0001, // Adding a slightly larger random component to ensure uniqueness
,
DESC,
Dense
)
)
VAR table_rank =
ADDCOLUMNS(
tbl_1_sorted,
// Columna "RowNumber" para asignar un número de fila único a cada registro
"RowNumber",
RANKX(
ALL(tbl_1_sorted), // Considera todos los registros de la tabla sin filtros
[Rank] +
RANKX(
ALL(tbl_1_sorted),
CALCULATE(
MAXX(tbl_1_sorted, tbl_1_sorted[CodigoArticulo]) // Valor máximo de CodigoArticulo para el desempate
),
,
ASC,
Dense // Usa Dense para clasificaciones consecutivas
) / COUNTROWS(ALL(tbl_1_sorted)), // Ajuste para evitar empates basado en el total de filas
,
ASC,
Dense // Usa clasificación ascendente y consecutiva para "RowNumber"
)
)
VAR final_ =
ADDCOLUMNS(
SUMMARIZE(
table_rank,
table_rank[CodigoArticulo],
table_rank[RowNumber],
"porc", SUM(table_rank[porc])
),
"RunningSum",
VAR CurrentRank = [RowNumber]
RETURN
CALCULATE(
SUM(table_rank[porc]),
FILTER(
ALL(table_rank),
table_rank[RowNumber] <= CurrentRank
&& table_rank[CodigoArticulo] = [CodigoArticulo]
)
)
)
VAR running_current = SUMX(final_,[RunningSum])
RETURN
running_current
the initital table will look something like this | CodigoArticulo | porc |
| abc234hj21 | 0.001269819292983 |
| bc234hj21 | 0.023401928347459 |
| bc234hj223 | 0.032123394040404 |
| bc234hj24gn | 0.011001110932900 |
If anyone has experience with handling ranks with tie-breakers in a measure like this, I’d appreciate any advice on how to make this running sum work dynamically with filters and rankings.
Thank you in advance for any help you can provide!