Formula in lens metrics in kibana

How to create a formula in lens-metrics that gives me the sum of 'value A' where there's a max in 'value B'.

I'm not sure I understood this part:

where there's a max in 'value B'.

Could you clarify with an example? Is that a query that you want to run?

I have 2 variables. One is a metric and the other could work either as a category or as a phase number.
What I want is to see the sum of the metric (total) for the last category. I could manually filter it but the phase number increases over time.

Could you share a sample document?

A clear example would be:
Category1/Phases goes 1,2,3,4,5,6, and so on.
Metric would be the value per category2 in each phase.
So, {
(category1: 1, category2: A, metric:5),
(category1: 1, category2: B, metric:7),
(category1: 2, category2: A, metric:8),
(category1: 2, category2: C, metric:4)}

What I'd like to do is to sum (get the total) category2 per category1
(category1: 2, category2: A, metric:8), (category1: 2, category2: C, metric:4 = 12) when it's the latest category1/phase, in this case 2, but as the dashboard refreses could be 1 or 5.

I still don't understand what exactly you are computing.
So, could you provide a full recreation script as described in About the Elasticsearch category. It will help to better understand what you are doing. Please, try to keep the example as simple as possible.

A full reproduction script is something anyone can copy and paste in Kibana dev console, click on the run button to reproduce your use case. It will help readers to understand, reproduce and if needed fix your problem. It will also most likely help to get a faster answer.

Have a look at the Elastic Stack and Solutions Help · Forums and Slack | Elastic page. It contains also lot of useful information on how to ask for help.