How to recursively count a specific level members which contains NULL values within hierarchy

StackOverflow https://stackoverflow.com/questions/20549276

  •  01-09-2022
  •  | 
  •  

Question

I've faced a misunderstanding while diving into the MDX. It's so different from regular SQL. I've processed my custom cube and developed a special calculated measure.

What does it do?

Well, It indicates whether it was no NULLs for all weeks within certain level(week, month, year) and count number of Shops which meet the condition.

My current hack:

WITH 
MEMBER [Measures].[Shop WBC]
AS SUM
([Shop].[Shop ID].[Shop ID].Members,
(IIF((Filter(Descendants([Time].[Week calendar], [Time].[Week calendar].[Week]),
[Measures].[Sales] IS NULL).Count) > 0, NULL, 1))
)

My testing select:

SELECT 
([Time].[Week calendar].[Week]) ON ROWS, 
([Shop].[Geo].[Region].Members, [Measures].[Shop WBC]) ON COLUMNS
FROM [Testable]
WHERE [Time].[Week].&[201301]:[Time].[Week].&[201319]

It returns 1 only (not NULL) for every shop, thus sum of shops.

However it returns the same value for all weeks (1 only). Why did it fail? I guess I don't get how Descendants function works in this case or something else? What do I miss? Hope my explanation is not so unclear.

Thanks in advance!

Was it helpful?

Solution

The way you wrote your query, the weeks on the row are irrelevant to the result, as your Filter statement overwrites the context of the Week calendar hierarchy. You should write your query as

WITH 
MEMBER [Measures].[Shop WBC]
AS SUM
([Shop].[Shop ID].[Shop ID].Members,
IIF((Filter(EXISTING [Time].[Week calendar].Members, [Measures].[Sales] IS NULL).Count > 0, NULL, 1)
)
SELECT 
([Time].[Week calendar].[Week]) ON ROWS, 
([Shop].[Geo].[Region].Members, [Measures].[Shop WBC]) ON COLUMNS
FROM [Testable]
WHERE [Time].[Week].&[201301]:[Time].[Week].&[201319]

Furthermore, in MDX, the WHERE clause is used much less frequently than in SQL. And, formally, it is illegal MDX to state the rows first. Proper MDX states the columns first and then the rows. However, Analysis Services is tolerant here. I would re-write the above query as

WITH 
MEMBER [Measures].[Shop WBC]
    AS SUM(
    [Shop].[Shop ID].[Shop ID].Members,
    IIF((Filter(EXISTING [Time].[Week calendar].Members, [Measures].[Sales] IS NULL).Count > 0, NULL, 1)
    )
SELECT 
    [Shop].[Geo].[Region].Members
    * { [Measures].[Shop WBC] }
ON COLUMNS,
    [Time].[Week calendar].&[201301] : [Time].[Week calendar].&[201319]
ON ROWS
FROM [Testable]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top