How to get the median value faster
The key issue can be that you run the query with the same parameters multiple times. I assume you have quite many records where Articolo/fase/tipo/etc are the same for you are looking for median. You did not state how many records you have but I think you could reduce the number of issued queries. So - without knowing too much details - I would

Collect unique Articolo/fase/tipo/etc values

Issue the queries only once for each combination

Update median values