A multidimensional database can be seen as a collection of multidimensional cubes, from which information is usually extracted by aggregation; aggregated data can be calculated either from cubes containing elemental data or from views in which partially aggregated data are stored. Thus, view materialization and run-time optimization through query rewriting become crucial issues in determining the overall performance. The capability of matching two queries is necessary to address both issues; unfortunately, most works in this field consider only simple categories of queries. In this paper we focus on a relevant class of queries, those modeled by Nested Generalized Projection / Selection / Join (NGPSJ) expressions, in which different aggregation functions may be applied in sequence to the same measure and selections may be formulated, at different granularities, on both dimensions and measures of the cube. Given two NGPSJ expressions, we show how to recursively compute their ancestor, i...