Check if level in any dimension hierarchy is [Foo] - ssas

In my Date Dimension I have 2 hierarchies:
[Year - Week - Date] and [Year - Month - Date]
I want to check in a Cube Calculation if the current level of the Date Dimension is [Date] (the lowest level) or something higher.
How can I achieve this?
Background: I need this to calculate how many working days there were in a period, for an employee.
I currently have this code (untested) that should do the trick for 1 hierarchy, but I guess this will fail when users are using the [Year - Week - Date] hierarchy.
CASE WHEN
[Date].[Year - Month - Date].CURRENTMEMBER.Level
IS
[Date].[Year - Month - Date].[Date]
THEN
//at day level,
//if there is any duration booked, this is a working day
IIF([Measures].[Duration] = 0,0,1)
ELSE
//at higher than day level,
//count days
COUNT(
// where duration > 0 (employee work day)
FILTER(
Descendants([Date].[Year - Month - Date].CURRENTMEMBER, [Date].[Year - Month - Date].[Date]),
[Measures].[Duration] > 0
)
)
END
tl;dr how do I make the above code also work for [Year - Week - Date] hierarchy in the cleanest way possible.

Let's assume the hierarchy (aka attribute) [Date].[Date] exists. If this is the case you can simplify :
COUNT(
FILTER( Existing [Date].[Date].members, [Measures].[Duration] > 0 )
)
The Existing will force to apply an autoexists on the [Date] dimension. This is mainly a performance improvement as it's avoid to evaluate (fact-vise) all tuples.
Once the former examples is clear, we can merge it with your version for the fastest solution (no need for the first iif) :
COUNT(
FILTER( Existing
Descendants([Date].[Year - Month - Date].CURRENTMEMBER, [Date].[Year - Month - Date].[Date],self)
, [Measures].[Duration] > 0 )
)
Further improvements may be possible adding a new measure with a different aggregation type or adding an iif to change which of the two hierarchies is used for descendants (e.g. the one where the currentmember and the defaulmember is not equal)

If you are looking for the cleanest way to calculate how many working days there were in a period, you have to emulate the behavior of regular measure. Otherwise you will get error or bad data in the case of a multiselect on [Date]. In addition, it is desirable to get rid of the Count(Filter(...)) expression to keep the block computation mode (see Optimizing Count(Filter(...)) expressions in MDX). To do this, follow these steps:
Go to the data source view.
Create a new named calculation next to the [Duration] column (in the same fact table).
Column name is "Working days", expression is "null".
Create a new regular measure based on "Working days" column. Aggregation function is Sum.
Write in the MDX script:
(
[Date].[Date].[Date].Members,
[Measures].[Working days]
) = Iif( [Measures].[Duration] > 0, 1, null );

IsLeaf() will tell you if a member is at the bottom level.

Look at SCOPE commands in your calculation script, I do something similar for my YMD calender and my YWD calendar:
CREATE MEMBER CurrentCube.Measures.Example AS NULL //Dummy will be calc'd later
SCOPE (DESCENDANTS([Date].[Calender Y M D],,AFTER));
Measures.Example = 1; //Fill in for monthly calcs
END SCOPE
SCOPE (DESCENDANTS([Date].[Calender Y W D],,AFTER));
Measures.Example = 2; //Fill in for weekly calcs
END SCOPE
The syntax with the ,,AFTER is to exclude the All member if I remember rightly, I'm trying to dif the link up but can't find it. Alternatively, if the calculation works well with the ALL member, just use SCOPE([Date].[Calender Y W D])

Related

MDX Dynamic dimension filter based on value of other dimension

How can I filter using values from two dimension in MDX?
The required result should include records where [Purchase Date].[Date] is before today minus number of years from [Accounting Date].[Year]. So, the result should include YoY records from today based on [Purchase Date].[Date] for each [Accounting Date].[Year] member.
I would like something like the following:
SELECT NON EMPTY [Measures].[Amount] ON 0,
NON EMPTY [Accounting Date].[Year].[Year].ALLMEMBERS ON 1
FROM [Tabular_Model]
WHERE (
NULL :
STRTOMEMBER("[Purchase Date].[Date].&["+ Format(DateAdd("YYYY", [Accounting Date].[Year].CURRENTMEMBER.MEMBER_VALUE - 2020, Now()),"yyyy-MM-ddT00:00:00") + "]")
)
But it fails with error: Execution of the managed stored procedure DateAdd failed with the following error: Microsoft::AnalysisServices::AdomdServer::AdomdException.
The syntax for 'All' is incorrect. (All).
Why CURRENTMEMBER.MEMBER_VALUE works for HAVING but not in my WHERE clause? What is the right way?
Try the following measure and query:
WITH
MEMBER [Measures].[Trailing Amount] as SUM({NULL :
STRTOMEMBER("[Purchase Date].[Date].&["+ Format(DateAdd("YYYY", [Accounting Date].[Year].CURRENTMEMBER.MEMBER_VALUE - 2020, Now()),"yyyy-MM-ddT00:00:00") + "]")}, [Measures].[Amount])
SELECT [Measures].[Trailing Amount] ON 0,
NON EMPTY [Accounting Date].[Year].[Year].MEMBERS ON 1
FROM [Tabular_Model]
If MDX doesn't perform as well as you hope, then you might consider adding the following DAX measure into your Tabular model. The following DAX query illustrates how to use it, but if you put this DAX measure into your model, you can query it with MDX queries and it should likely perform better than an MDX calculation:
define
measure 'Your Table Name Here'[Trailing Sales] =
VAR YearOffset = SELECTEDVALUE('Accounting Date'[Year]) - 2020
VAR NowDate = NOW()
VAR EndDate = DATE(YEAR(NowDate)+YearOffset,MONTH(NowDate),DAY(NowDate))
RETURN CALCULATE([Amount], 'Purchase Date'[Date] <= EndDate)
evaluate ADDCOLUMNS(ALL('Accounting Date'[Year]),"Trailing Sales",[Trailing Sales])

Get schedules of particular date from date ranges with MDX query

I already posted this problem many times, but unfortunately nobody could understand, I m sorry for my poor english :(
I reformulate ...
I have following fact table
I want to get records that match with a particular date and day of week (JOUR) in all dates range (DATE_DEB, DATE_FIN)
I can do that in SQL like this:
SELECT DATE_DEB,
DATE_FIN,
ID_HOR,
to_char(HR_DEB,'hh24:mi:ss') as HR_DEB,
to_char(HR_FIN,'hh24:mi:ss') as HR_FIN,
JOUR
FROM GRP_HOR HOR, GRP
WHERE GRP.ID_ACTIV_GRP = HOR.ID_ACTIV_GRP
AND TO_DATE('1998-01-08', 'YYYY-MM-DD') between DATE_DEB and DATE_FIN
AND 1 + TRUNC(TO_DATE('1998-01-08', 'YYYY-MM-DD')) - TRUNC(TO_DATE('1998-01-08', 'YYYY-MM-DD'), 'IW') = JOUR
So, I'll get 29 records (see below) which included in each range and match with the day of week (JOUR ), after that I want to enlarge them by hours (HR_DEB, HR_FIN).
The problem is, what's how the best way to do this ?
Create 2 date dimension and link them with DATE_DEB, DATE_FIN.
Create 2 Time dimension and link them with HR_DEB, HR_FIN.
How can I implement the between SQL clause in MDX ? Or geater than or Less than ?
Thank you in advance.
OUTPUT :
To specify a range of dates in MDX you just use the colon operator :
Here is the documentation on MSDN: https://learn.microsoft.com/en-us/sql/mdx/range-mdx?view=sql-server-2017
This is the example they give:
With Member [Measures].[Freight Per Customer] as
(
[Measures].[Internet Freight Cost]
/
[Measures].[Customer Count]
)
SELECT
{[Ship Date].[Calendar].[Month].&[2004]&[1] : [Ship Date].[Calendar].[Month].&[2004]&[3]} ON 0,
[Product].[Category].[Category].Members ON 1
FROM
[Adventure Works]
WHERE
([Measures].[Freight Per Customer])

how to get the 100 days before date from Todays Date in Dimdatedimension

I have small doubt in ssas cube datasource view level.
I want add one new column(last100days) in Dimdate timension and that column show last 100 days information.
I Tried in sql server level like below query
add new column(last100days) in dimdate dimension
1)update dimdate set last100days='01-01-1900'
2)update dimdate
set last100days=[StandardDate]
WHERE [StandardDate] >= DATEADD(day,-100, getdate())
and [StandardDate] <= getdate()
That time i will get accurate result in dimdate dimension.
same way I tried In datasoure view level in dimdatedimension level right click on that and choose new namedcalculation and I give column name is last100days and enter expression like
[StandardDate] >= DATEADD(day,-100, getdate())
and [StandardDate] <= getdate()
that time it show error like below
TITLE: Microsoft Visual Studio
Deferred prepare could not be completed.
Statement(s) could not be prepared.
Incorrect syntax near the keyword 'AS'.
Incorrect syntax near the keyword 'update'.
BUTTONS:
OK..I
-
enter code here
add new column and that column have from today to last100 days dates .please help me how to resolve this issuse in ssas cube side
You need to enter an expression that returns a value. All yours does is test conditions.
Try this instead:
CASE
WHEN [StandardDate] >= DATEADD(day,-100, getdate()) AND [StandardDate] <= getdate()
THEN [StandardDate]
ELSE NULL
END
You don't really need to create a measure for this. You need a new column in your date dimension to be indicative of whether the date is older than 100 days or not. Let's say that column is called RollingLast100days. You need to make a minor adjustment to #tab-alleman's code.
CASE
WHEN DATEDIFF(dd, [StandardDate], GETDATE()) <=100
THEN 1
ELSE 0
END
Now that the column is ready, if you want to see only last 100 days worth of data, you just need to have a small additional condition.
WHERE [Dim Date].[Date].RollingLast100days = 1
e.g. Fetching the sales for the last 100 days only:
SELECT [Measures].[Sales Amount] ON 0
FROM [YourCube]
WHERE [Dim Date].[Date].RollingLast100days = 1
Fetching a list of products sold in the last 100 days:
SELECT [Measures].[Sales Amount] ON 0,
Product.Products.MEMBERS ON 1
FROM [YourCube]
WHERE [Dim Date].[Date].RollingLast100days = 1
Hope this helps.

Parents of set in MDX

I have a filter that selects a specific date in my date dimension, This will be passed in as a parameter into the MDX query.
Filter([Date Dimension].[Calendar Year Hierarchy].[Actual Date].members,
[Date Dimension].[Actual Date].CurrentMember.Properties( "Name" ) = '2011-09-01 00:00:00.000')
I would now like to select the weeks and/or months in the hierarchy above that.
[Date Dimension].[Calendar Year Hierarchy].[Month]
[Date Dimension].[Calendar Year Hierarchy].[Calendar Week]
I have tried several functions without much luck such as .Parent and DrillupLevel
I could be using them wrong or in the wrong spot,
thanks for the help
You could use the function GENERATE to get all ascendants:
Generate
(
{Filter([Date Dimension].[Calendar Year Hierarchy].[Actual Date].members,
[Date Dimension].[Actual Date].CurrentMember.Properties( "Name" ) =
'2011-09-01 00:00:00.000')},
{Ascendants([Date Dimension].[Calendar Year Hierarchy].CurrentMember)}
)
Query using Adventure Works:
Select
{[Measures].[Internet Sales Amount]} On Columns,
{Generate(
{Filter([Date].[Calendar].[Date].members,[Date].[Calendar].CurrentMember.Properties("Name") = 'April 1, 2004')},
{Ascendants([Date].[Calendar].CurrentMember)})} On Rows
From [Adventure Works]
If you know the level you're looking for you can use MDX Ancestor function instead of parent:
Ancestor([Date Dimension].[Calendar Year Hierarchy].currentmember,
[Date Dimension].[Calendar Year Hierarchy].[Month])
If no, it's fine using parent function. Note, using properties is not the quickest method to filter (for very large sets).
Why not using to StrToMember MDX function ?
StrToMember( ... here build your member with a string ... )
or if you can edit you mdx directly creating the statement directly with the help of a string builder ?
so the answer i have at the moment is
Filter([Date Dimension].[Calendar Year Hierarchy].[Actual
Date].members, [Date Dimension].[Actual
Date].CurrentMember.Properties( "Name" ) = '2011-09-01 00:00:00.000')
.item(0).parent
using the .item[0] to get the item in the set
and the .parent to get that items parent (in my case i am actually calling it 3 times)
if anyone has any better ideas would love to here them.
You can use STRTOSET and for each input parameter replace ] with ].Parent, this way you will have set of parents.

multiple dimension restrictions in a MDX where clause

I have the following problem. If I query values with a keyfigure which is a function I can't specify multiple values of the same dimension restriction, but if it is not a function it works.
So this works:
SELECT {[Measures].[Netto]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00]),
NonEmpty([Time].[Month].[Month].&[2008-04-01T00:00:00])})
But this doesn't:
SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00]),
NonEmpty([Time].[Month].[Month].&[2008-04-01T00:00:00])})
And this also works:
SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where
({NonEmpty([Time].[Month].[Month].&[2008-03-01T00:00:00])})
I guess the solution is something like adding the where clause to the header but I really like this solution because it's so simple.
The Calucated function is:
CREATE MEMBER CURRENTCUBE.[MEASURES].Ultimo
AS (iif ((not [Time].[Year - Month - Date].currentmember is [Time].[Year - Month - Date].defaultmember),
IIF(NOT ([Measures].[LagerStk] = 0),
Sum([Time].[Year - Month - Date].[Date].members(0):
ClosingPeriod([Time].[Year - Month - Date].[Date]),
[Measures].[LagerStk]), NULL)
,
IIF(NOT ([Measures].[LagerStk] = 0),
Sum([Time].[Year - Week - Date].[Date].members(0):
ClosingPeriod([Time].[Year - Week - Date].[Date]),
[Measures].[LagerStk]), NULL))),
VISIBLE = 1;
The code is inspired from this and modified for two hierarchies in the time dimension: http://www.sqlserveranalysisservices.com/OLAPPapers/InventoryManagement%20in%20AS2005v2.htm
This is on SQL server 2005 Enterprise edition.
Ok, this works:
WITH MEMBER [Time].[Month].a AGGREGATE
({[Time].[Month].[Month].&[2008-03-01T00:00:00],
[Time].[Month].[Month].&[2008-04-01T00:00:00]})
SELECT {[Measures].[CalculatedFunction]} on columns FROM TDC where a
The problem is in your calculated measure. You are using .CurrentMember and ClosingPeriod without a specific member reference which implies a call to .CurrentMember. When you have set in the WHERE clause there is no "Current" member - there are multiple current members. Re-writting your MDX to something like the following should allow it to work with multiple members in the WHERE clause.
CREATE
MEMBER CURRENTCUBE.[MEASURES].Ultimo AS NULL;
SCOPE ([MEASURES].Ultimo);
SCOPE ([Time].[Year - Month - Date].[All]);
this = IIF
(
(NOT
[Measures].[LagerStk] = 0)
,Sum
(
NULL:Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0)
,[Measures].[LagerStk]
)
,NULL
);
END SCOPE;
SCOPE ([Time].[Year - Week - Date].[All]);
this = IIF
(
(NOT
[Measures].[LagerStk] = 0)
,Sum
(
NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0)
,[Measures].[LagerStk]
)
,NULL
)
);
END SCOPE;
END SCOPE;
I am using SCOPE on the All members of the two dimensions, this should be fast that the out IIF and will also avoid one reference to .CurrentMember. I then replaced the ClosingPeriod() call with Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0) what this does is to get the set of date members that exist in the current context, the Tail() call then gets the last on of these as a single member set and the .Item(0).Item(0) calls get the first member from the first tuple of that set.
Obviously, not having access to your cube, I can't test any of this. The issue you reported in your comment could relate to either an incorrect reference to the All members (I may have a different naming format to the one in your cube) or it may be related to the IIF() statement. I'm not sure that the check for 0 is being evaluated in the correct context
You could try testing without the IIF()
CREATE
MEMBER CURRENTCUBE.[MEASURES].Ultimo AS NULL;
SCOPE ([MEASURES].Ultimo);
SCOPE ([Time].[Year - Month - Date].[All]);
this = Sum
(
NULL:Tail(Existing [Time].[Year - Week - Date].[Date],1).item(0).item(0)
,[Measures].[LagerStk]
);
END SCOPE;
SCOPE ([Time].[Year - Week - Date].[All]);
this = Sum
(
NULL:Tail(Existing [Time].[Year - Month - Date].[Date],1).Item(0).Item(0)
,[Measures].[LagerStk]
);
END SCOPE;
END SCOPE;