MDX query with nested aggregations - mdx

WITH
MEMBER [Measures].[newCalculatedMeasure] AS
Sum
(
Filter
(
Descendants
(
[Date].[28 Days Month Calendar].CurrentMember
,2
,LEAVES
)
,
[Measures].[mymeasure] * 10
>
Avg
(
Filter
(
Descendants
(
[Date].[28 Days Month Calendar].CurrentMember
,2
,LEAVES
)
,
[Measures].[mymeasure] > 0
)
,[Measures].[mymeasure]
)
)
,[Measures].[mymeasure]
)
SELECT
[Date].[28 Days Month Calendar].MEMBERS ON 0
,[Measures].[newCalculatedMeasure] ON 1
FROM [cube];
Above query is not evaluating the inside average function, whereas if i replace that with the actual average, its working fine
Can somebody tell me whats wrong with the above measure..

Does splitting the measure into named sets help with this context issue?
WITH
SET [MYSET] AS
Descendants
(
[Date].[28 Days Month Calendar].CurrentMember
,2
,LEAVES
)
SET [MYSETFILTERED] AS
Filter
(
[MYSET]
,
[Measures].[mymeasure] > 0
)
MEMBER [Measures].[newCalculatedMeasure] AS
Sum
(
Filter
(
[MYSET]
,
[Measures].[mymeasure] * 10 > Avg([MYSETFILTERED],[Measures].[mymeasure])
)
,[Measures].[mymeasure]
)
SELECT
[Date].[28 Days Month Calendar].MEMBERS ON 0
,[Measures].[newCalculatedMeasure] ON 1
FROM [cube];
Named sets with aggregates can sometimes impact performance so please excuse me if the above slows everything up.

Related

Querying the same column for 3 different values

I'm trying hard to extract the data in the format I need, but unsuccessful til now.
I have the following table
id_ticket, date_ticket, office_ticket, status_ticket
I need the query to return me, for EVERY MONTH, and always for the same OFFICE:
the number of tickets (COUNT) with any status
the number of tickets (COUNT) with status = 5
the number of tickets (COUNT) with status = 6
Month
Year
The query I made to return ONLY the total amount of tickets with any status was this. It worked!
SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
Returning the total amount of ticket with status=5
SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1 AND status_ticket = 5
GROUP BY
YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
But I need the return to be something like:
Year Month Total Status5 Status6
2018 1 15 5 3
2018 2 14 4 5
2018 3 19 2 8
Thank you for your help.
You are close. You can use a CASE Expression to get what you need:
SELECT
COUNT (id_ticket) as TotalTicketsPerMonth,
SUM(CASE WHEN status_ticket = 5 THEN 1 END) as Status5,
SUM(CASE WHEN status_ticket = 6 THEN 1 END) as Status6,
'sYear' = YEAR (date_ticket),
'sMonth' = MONTH (date_ticket)
FROM crm_vw_Tickets
WHERE office_ticket = 1
GROUP BY YEAR (date_ticket), MONTH (date_ticket)
ORDER BY sYear ASC, sMonth ASC
The following code builds off JNevill's answer to include summary rows for "missing" months, i.e. those with no tickets, as well as months with tickets. The basic idea is to create a table of all of the months from the first to the last ticket, outer join the ticket data with the months and then summarize the data. (Tally table, numbers table and calendar table are more or less applicable terms.)
It is a Common Table Expression (CTE) that contains several queries that work step-by-step toward the result. You can see the results of the intermediate steps by replacing the final select statement with one of the ones commented out above it.
-- Sample data.
declare #crm_vw_Tickets as Table ( id_ticket Int Identity, date_ticket Date, office_ticket Int, status_ticket Int );
insert into #crm_vw_Tickets ( date_ticket, office_ticket, status_ticket ) values
( '20190305', 1, 6 ), -- Shrove Tuesday.
( '20190501', 1, 5 ), -- May Day.
( '20190525', 1, 5 ); -- Towel Day.
select * from #crm_vw_Tickets;
-- Summarize the data.
with
-- Get the minimum and maximum ticket dates for office_ticket 1.
Limits as (
select Min( date_ticket ) as MinDateTicket, Max( date_ticket ) as MaxDateTicket
from #crm_vw_Tickets
where office_ticket = 1 ),
-- 0 to 9.
Ten ( Number ) as ( select * from ( values (0), (1), (2), (3), (4), (5), (6), (7), (8), (9) ) as Digits( Number ) ),
-- 100 rows.
TenUp2 ( Number ) as ( select 42 from Ten as L cross join Ten as R ),
-- 10000 rows. We'll assume that 10,000 months should cover the reporting range.
TenUp4 ( Number ) as ( select 42 from TenUp2 as L cross join TenUp2 as R ),
-- 1 to the number of months to summarize.
Numbers ( Number ) as ( select top ( select DateDiff( month, MinDateTicket, MaxDateTicket ) + 1 from Limits ) Row_Number() over ( order by ( select NULL ) ) from TenUp4 ),
-- Starting date of each month to summarize.
Months as (
select DateAdd( month, N.Number - 1, DateAdd( day, 1 - Day( L.MinDateTicket ), L.MinDateTicket ) ) as StartOfMonth
from Limits as L cross join
Numbers as N ),
-- All tickets assigned to the appropriate month and a row with NULL ticket data
-- for each month without tickets.
MonthsAndTickets as (
select M.StartOfMonth, T.*
from Months as M left outer join
#crm_vw_Tickets as T on M.StartOfMonth <= T.date_ticket and T.date_ticket < DateAdd( month, 1, M.StartOfMonth ) )
-- Use one of the following select statements to see the intermediate or final results:
--select * from Limits;
--select * from Ten;
--select * from TenUp2;
--select * from TenUp4;
--select * from Numbers;
--select * from Months;
--select * from MonthsAndTickets;
select Year( StartOfMonth ) as SummaryYear, Month( StartOfMonth ) as SummaryMonth,
Count( id_ticket ) as TotalTickets,
Coalesce( Sum( case when status_ticket = 5 then 1 end ), 0 ) as Status5Tickets,
Coalesce( Sum( case when status_ticket = 6 then 1 end ), 0 ) as Status6Tickets
from MonthsAndTickets
where office_ticket = 1 or office_ticket is NULL -- Handle months with no tickets.
group by StartOfMonth
order by StartOfMonth;
Note that the final select uses Count( id_ticket ), Coalesce and an explicit check for NULL to produce appropriate output values (0) for months with no tickets.

Getting error when Calculating the Sum of premium values using DAX on a slowly changing dimension

Using DAX - I need to calculate the total premium amount for policies with a certain status - using a slowly changing dimension as a source.
This is something that's running within SSAS tabular model.
The solution has two tables - dim_date (which is a calendar table) and a Dim_contract (which have all my policies listed)
The Dim_Contract table is a slowly changing dimension.
The table format:
DW_ContractID DW_EffectiveFromDate contract_number actual_recurring_collection ContractStatusTLA
-2145825896 22 August 2018 4303140 80 PIN
-2145627139 26 September 2018 4303140 80 INF
-2145428382 09 October 2018 4303140 80 Can
-2145229625 21 August 2018 4303142 100 PIN
-2145030868 22 September 2018 4303142 100 NTU
-2144832111 02 September 2018 4303999 50 PIN
-2144633354 03 September 2018 4303999 50 INF
I've done a calculation to count the policies - which work 100%.
With this calc, we count the number of policies for each time period. (depending what the user selects)
Example - if we want to count the number of policies as at the end of September per status we should get:
INF: 2 (This is counting policy numbers 4303140 and 4303999 as their last status is INF)
CAN: 0
NTU: 1
The code used to do the counts:
PolicyCount_NTU :=
IF (
MIN ( DIM_Date[Date] )
>= CALCULATE ( MIN ( DIM_Contract[DW_EffectiveFromDate] ), ALL ( DIM_Contract ) ),
IF (
MIN ( DIM_Date[Date] )
<= CALCULATE ( MAX ( DIM_Contract[DW_EffectiveFromDate] ), ALL ( DIM_Contract ) ),
CALCULATE (
COUNTROWS (
FILTER (
DIM_Contract,
DIM_Contract[DW_ContractID]
= CALCULATE (
MAX ( DIM_Contract[DW_ContractID] ),
ALL ( DIM_Contract ),
DIM_Contract[contract_number] = EARLIER ( DIM_Contract[contract_number] ),
( DIM_Contract[DW_EffectiveFromDate] ) <= VALUES ( DIM_Date[Date] )
)
)
),
LASTDATE ( DIM_Date[Date] ),
DIM_Contract[ContractStatusTLA] = "NTU"
)
)
)
The problem comes in with the calc to get the sum of the amounts...
I used this code:
PolicyAPI_NTU :=
IF (
MIN ( DIM_Date[Date] )
>= CALCULATE ( MIN ( DIM_Contract[DW_EffectiveFromDate] ), ALL ( DIM_Contract ) ),
IF (
MIN ( DIM_Date[Date] )
<= CALCULATE ( MAX ( DIM_Contract[DW_EffectiveFromDate] ), ALL ( DIM_Contract ) ),
CALCULATE (
SUM ( DIM_Contract[actual_recurring_collection] ),
(
FILTER (
DIM_Contract,
DIM_Contract[DW_ContractID]
= CALCULATE (
MAX ( DIM_Contract[DW_ContractID] ),
ALL ( DIM_Contract ),
DIM_Contract[contract_number] = EARLIER ( DIM_Contract[contract_number] ),
DIM_Contract[DW_EffectiveFromDate] < VALUES ( DIM_Date[Date] )
)
)
),
LASTDATE ( DIM_Date[Date] ),
DIM_Contract[ContractStatusTLA] = "NTU"
)
)
)
Using the last piece of code to get the SUM of the amounts doesn't work - I get an error: Error: Calculation error in measure 'DIM_Contract'[PolicyAPI_NTU]: A table of multiple values was supplied where a single value was expected.
I suspect your problem is here
DIM_Contract[DW_EffectiveFromDate] < VALUES ( DIM_Date[Date] )
The DAX doesn't know how to do a comparison if DIM_Date[Date] has multiple values.
Try using a MAX or MIN or LASTDATE or something similar instead of VALUES.

YTD Measure in DAX Studio doesn't show any value for several dates

Trying to calculate YTD for several dates in DAX STUDIO according to https://www.daxpatterns.com/time-patterns/ guide
I've created a measure in my model, which gets the job done when I use Date Dimension and calculates YTD for every date
CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
But when I'm trying to reproduce the same result using DAX Studio, I get correct result only when I filter CALCULATETABLE for a certain date
This code works perfectly:
EVALUATE
CALCULATETABLE(
ADDCOLUMNS (
VALUES ( 'Date'[Date] ),
"YTD", CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
)
,
'Date'[Date] = DATE(2018,5,1)
)
This code is expected to return YTD for every date in rows, but, unfortunately it doesn't. What am I doing wrong?:
EVALUATE
CALCULATETABLE(
ADDCOLUMNS (
VALUES ( 'Date'[Date] ),
"YTD", CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
)
,
'Date'[Date] >= DATE(2018,5,1)
)
The only difference is = vs >=, but I get empty result for all the rows
Nothing is wrong with the way you defined your measure.
However, when testing the measure, you should try to write your DAX query in a way similar to what client tools like Power BI would do:
EVALUATE
SUMMARIZECOLUMNS(
'Date'[Date],
FILTER('Date', 'Date'[Date] >= DATE(2018,5,1)),
"YTD", CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
)
or even better:
DEFINE MEASURE 'Sales'[Sales Amt YTD] = CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
EVALUATE
SUMMARIZECOLUMNS(
'Date'[Date],
FILTER('Date', 'Date'[Date] >= DATE(2018,5,1)),
"YTD", [Sales Amt YTD]
)
The issue with the way you wrote it, using CALCULATETABLE, is that you create an outside filter context on the 'Date'[Date] column that contains all dates starting from 2018-05-01. When evaluating the YTD logic inside the FILTER statement, MAX('Date'[Year]) uses this filter context, so that it returns whatever year is the largest on your entire 'Date' table (for example 2025).
Remember, that the CALCULATE function only applies a context transition (row context to filter context) when evaluating the first argument. The filter arguments are evaluated on the original filter context.
If you want to stick with your syntax, you could write an additional CALCULATE to force the context transition to apply also to the 2nd argument of the inner CALCULATE call:
EVALUATE
CALCULATETABLE(
ADDCOLUMNS (
VALUES ( 'Date'[Date] ),
"YTD",
CALCULATE( // Additional CALCULATE to force context transition on filter arguments
CALCULATE (
[Sales Amt],
FILTER (
ALL ( 'Date' ),
'Date'[Year] = MAX ( 'Date'[Year] )
&& 'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
)
),
'Date'[Date] >= DATE(2018,5,1)
)
This would be the same as referencing the measure directly, as referencing a measure always does an implicit CALCULATE:
EVALUATE
CALCULATETABLE(
ADDCOLUMNS (
VALUES ( 'Date'[Date] ),
"YTD", [Sales Amt YTD]
),
'Date'[Date] >= DATE(2018,5,1)
)

Create Set to get Last month of Each Year

I would like to create a set that returned the last Date for each year. For example all previous years would return December, but the current year would only return the current month.
WITH
SET testset AS
NonEmpty
(
Generate
(
{
OpeningPeriod([Date].[Calendar].[Month])
:
ClosingPeriod([Date].[Calendar].Month)
}
,{[Date].[calendar].CurrentMember}
)
,[Measures].[Sale Amount]
)
SELECT
NON EMPTY
(
[Measures].[Sale Amount]
,[Date].[Year].[Year]
) ON 0
,NON EMPTY
[testset] ON 1
FROM [Cube]
Here is an example of a script that returns the values for each month. I've tried using tail and lastchild, but that only returns the most recent. I would like it to return for every Year.
In terms of just the last month - ignoring whether there is data for it or not the following:
WITH
SET [AllYears] AS
[Date].[Calendar].[Calendar Year].MEMBERS
SET [LastMths] AS
Generate
(
[AllYears] AS S
,Tail
(
Descendants
(
S.CurrentMember
,[Date].[Calendar].[Month]
)
,1
)
)
SELECT
{} ON 0
,[LastMths] ON 1
FROM [Adventure Works];
Returns this:
If I want to adapt the above so that it is the last month per year that has data for a specific measure then wrap NonEmpty around the set created by Descendants:
WITH
SET [AllYears] AS
[Date].[Calendar].[Calendar Year].MEMBERS
SET [LastMths] AS
Generate
(
[AllYears] AS S
,Tail
(
NonEmpty //<<new
(
Descendants
(
S.CurrentMember
,[Date].[Calendar].[Month]
)
,[Measures].[Internet Sales Amount] //<<new
)
,1
)
)
SELECT
{} ON 0
,[LastMths] ON 1
FROM [Adventure Works];
It now gives us this:
We can then add in the tuple you have on rows (I have used the attribute hierarchy this time for years as [Date].[Calendar] is already in use)
WITH
SET [AllYears] AS
[Date].[Calendar].[Calendar Year].MEMBERS
SET [LastMths] AS
Generate
(
[AllYears] AS S
,Tail
(
NonEmpty
(
Descendants
(
S.CurrentMember
,[Date].[Calendar].[Month]
)
,[Measures].[Internet Sales Amount]
)
,1
)
)
SELECT
NON EMPTY
(
[Measures].[Internet Sales Amount]
,[Date].[Calendar Year].[Calendar Year]
) ON 0
,[LastMths] ON 1
FROM [Adventure Works];
Now we get this:
#Whytheq has already given a very good solution. Treat this as an alternative. This might be a tad faster as it doesn't use the GENERATE function (not sure though!).
Have a calculated/cube measure which basically tells whether a month is the last month of the year. Then select those months out of the set of months.
with member measures.islastchild as
iif
(
[Date].[Calendar].currentmember is
[Date].[Calendar].currentmember.parent.parent.parent.lastchild.lastchild.lastchild,
1,
null
)
The member measures.islastchild returns 1 if the month is the last month of the year. Else it would return null.
set lastmonths as
filter(
[Date].[Calendar].[Month].members,
measures.islastchild = 1
)
The set lastmonths is then the set you need.
edit
To further improve the performance, you can NonEmpty function instead of the iterative FILTER function.
set lastmonths as
NonEmpty(
[Date].[Calendar].[Month].members,
measures.islastchild
)
select lastmonths on 1,
{} on 0
from [Adventure Works]
EDIT 2: To get the last non month with sales
with member measures.islastnonemptychild as
iif
(
[Date].[Calendar].currentmember is
TAIL(NonEmpty([Date].[Calendar].currentmember.parent.parent.parent.lastchild.lastchild.children, [Measures].[Sale Amount])).ITEM(0),
1,
null
)
set nonemptylastmonths as
NonEmpty(
[Date].[Calendar].[Month].members,
measures.islastnonemptychild
)

Moving Average of Last 24 months

I have this calculated member which calculates a moving average for the last 12 months:
iif(IsEmpty(Sum({[Time].[Month].CurrentMember:NULL},
[Measures].[Count])), NULL,
Avg
(
[Time].[Month].CurrentMember.Lag(11) :
[Time].[Month].CurrentMember,
[Measures].[Count]
))
The iif condition is in place because I don't want to get values for future months (with no value), which I do get without it.
What I want to do is have this measure only for the last 24 months since the last not empty month.
I've tried with Tail and Lag but with no luck (I would post my attempts here but after many tries I deleted them and would really not know where to begin again).
Thanks to #whytheq this is the final solution that I used:
CREATE DYNAMIC SET CURRENTCUBE.[FirstEmptyMonth]
AS { Tail
(
NonEmpty
(
[Time].[Month].MEMBERS
,[Measures].[Count]
)
,1
).Item(0).NextMember };
CREATE DYNAMIC SET CURRENTCUBE.[MonthsToIgnore]
AS {[FirstEmptyMonth].Item(0) : NULL}
+
{NULL : [FirstEmptyMonth].Item(0).Lag(25)} ;
CREATE MEMBER CURRENTCUBE.[Measures].[Moving Average]
AS IIF
(
Intersect({[Time].[Month].CurrentMember},[MonthsToIgnore]).Count = 1
,null
,Avg
(
[Time].[Month].CurrentMember.Lag(11) : [Time].[Month].CurrentMember
,[Measures].[Count]
)
);
In AdvWrks I've got this:
WITH
SET [FutureMonthsWithNoData] AS
{
Tail
(
NonEmpty
(
[Date].[Calendar].[Month].MEMBERS
,[Measures].[Internet Sales Amount]
)
,1
).Item(0).NextMember
: NULL
}
MEMBER [Measures].[blah] AS
IIF
(
Intersect
(
{[Date].[Calendar].CurrentMember}
,[FutureMonthsWithNoData]
).Count
= 1
,null
,1
)
SELECT
{
[Measures].[Internet Sales Amount]
,[Measures].[blah]
} ON 0
,[Date].[Calendar].[Month].MEMBERS ON 1
FROM [Adventure Works];
It returns this:
So what I am saying is that you could create this initial set of FutureDatesWithNoData and then use that set to create a condition within your script. The set would be (I think) this in your cube:
SET [FutureMonthsWithNoData] AS
{
Tail
(
NonEmpty
(
[Time].[Month].[Month].MEMBERS
,[Measures].[Count]
)
,1
).Item(0).NextMember
: NULL
}
Your measure would then be as follows:
IIF
(
Intersect
(
{[Time].[Month].CurrentMember}
,[FutureMonthsWithNoData]
).Count
= 1
,NULL
,Avg
(
[Time].[Month].CurrentMember.Lag(11) : [Time].[Month].CurrentMember
,[Measures].[Count]
)
)
If you want to also exclude months prior to 24 months ago then this script sums up the logic:
WITH
SET [FistEmptyMonth] AS
{
Tail
(
NonEmpty
(
[Date].[Calendar].[Month].MEMBERS
,[Measures].[Internet Sales Amount]
)
,1
).Item(0).NextMember
}
SET [MonthsToIgnore] AS
{[FistEmptyMonth].Item(0) : NULL}
+
{NULL : [FistEmptyMonth].Item(0).Lag(24)}
MEMBER [Measures].[blah] AS
IIF
(
Intersect({[Date].[Calendar].CurrentMember},[MonthsToIgnore]).Count = 1
,null
,1
)
SELECT
{[Measures].[Internet Sales Amount]} ON 0
,[Date].[Calendar].[Month].MEMBERS ON 1
FROM [Adventure Works];