I'm trying to find the top 5 items sales based on the turnover but I keep receiving this error : The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value.
Top_Five_Items_Turnover =
VAR X =
CALCULATE(
TOPN(
5,
SUMMARIZE(
Sales,
Sales[item],
"Top_Five",
Sales[item]
),
[Turnover], DESC
),
Sales[item]
)
RETURN
X
Hi you cannot return a entire table using a measure. instead return values.
Top 5 =
VAR totalSales =
SUM ( Sales[item] )
RETURN
CALCULATE (
totalSales,
FILTER (
VALUES ( Sales[item] ),
IF (
RANKX ( ALL ( Sales[item]), [Turnover], desc) <= 5,
[Total Sales],
BLANK ()
)
)
)
Related
I have a table my_data with the following columns: CATEGORY, SUPPLIER and AMOUNT. I have created measures to calculate the total amount:
Total_Amount := SUM(my_data[AMOUNT])
and to do an ABC classification, I created a ranking:
Ranking:=IF (
ISBLANK ( [Total_Amount] ),
BLANK (),
RANKX (
FILTER (
ALL ( my_data[CATEGORY], my_data[SUPPLIER] ),
my_data[CATEGORY] = MAX ( my_data[CATEGORY] )
),
CALCULATE ( [Total_Amount] )
)
)
a Running Total:
Running_Total:=VAR current_rank = [Ranking]
RETURN
SUMX (
FILTER (
ALL ( my_data[SUPPLIER] ),
[Ranking] <= current_rank
),
[Total_Amount]
)
a Running Total %:
Running_Total(%):=DIVIDE (
[Running_Total],
SUMX ( ALL ( my_data[SUPPLIER] ), [Total_Amount] ),
BLANK ()
)
and the ABC classifier:
ABC_class:=IF (
ISBLANK ( [Total_Amount] ),
BLANK (),
SWITCH (
TRUE (),
[Running_Total(%)] <= [Class_A], "A",
[Running_Total(%)] <= [Class_B], "B",
"C"
)
)
Now, my problem. I have several slicers. Once of them is to choose A, B and/or C from the ABC classification. Note, that in my data there is no column with A, B or C data. The classification is only a measure. So I used a trick to be able to connect the slicer to my Pivot Table and that works fine. PROBLEM: I do not manage to get the right subtotals and grand totals for the following measure:
measure:=VAR Selected_Class =
ALLSELECTED ( ABC_table[Class] )
VAR Supplier_Class =
CALCULATE (
[ABC_class],
ALLEXCEPT (
my_data,
my_data[CATEGORY],
my_data[SUPPLIER],
Period_Table[YEAR]
)
)
RETURN
IF (
HASONEFILTER ( my_data[SUPPLIER] ),
IF (
CONTAINSROW ( Selected_Class, Supplier_Class ),
[Total_Amount],
BLANK ()
),
SUMX (
FILTER (
SUMMARIZECOLUMNS (
StockMvts[SUPPLIER],
"total", [Total_Purchased(EUR)],
"class", [ABC_TotPurchased_byCat&Sup]
),
CONTAINSROW(Selected_Class, [class])
),
[total]
)
)
This last measure doesn't work. It gives an error. The problem is in the SUMX for the subtotals and grand totals. How do I make it to sum only the values of [Total_Amount] for the [SUPPLIER] where the [ABC_class] measure results in one of the values selected in the ABC slicer?
Note, I'm using Power Pivot on Excel.
Thank you!
Question
What is an efficient way to create a calculated column finding the last value of my DATE column, using the ModifiedOn column, per ID? I don't want the MAX date, just the last record (even if the last record is the minimum). Also, my table is a calculated column.
Example Table
ID
DATE
ModifiedOn
A
2/4/2020
1/16/2019
A
2/5/2020
1/17/2019
B
3/2/2020
2/7/2020
B
3/3/2020
2/8/2020
B
3/1/2020
2/9/2020
Current Formula
LastRecord =
VAR Max_Date =
CALCULATE (
MAX ( 'Table1'[ModifiedOn] ),
ALLEXCEPT ( 'Table1', 'Table1'[ID] )
)
RETURN
IF (
Table1[ModifiedOn] = Max_Date,
Table1[DATE]
)
Current Results
But using the formula I get a calculated column that looks like this:
I keep getting blanks where they should be filled with the LAST recorded date of that ID.
Use the following dax formula to create the expected column:
Column =
VAR __id = 'Table'[ID]
VAR __lastMod =
CALCULATE(
MAX( 'Table'[ModifiedOn] ),
FILTER( 'Table', 'Table'[ID] = __id )
)
VAR __lastDate =
CALCULATE(
MAX( 'Table'[Date] ),
FILTER( 'Table', 'Table'[ID] = __id && 'Table'[ModifiedOn] = __lastMod )
)
Return __lastDate
How to calculate rank within Category defined on sales level. Say, that we want to label products with Sales above some threshold with Category "high", and below that threshold with Category "low".
Here is a sample data.
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WcisqzSwpVtJRSiwoyEkF0oZKsTpIwkmJeUAIZJigipfn56QlpRYVVQLZpqhSyRlQcWOweFhqempJYlJOKlgusagovwS7XEF+SWJJPtwJKHL5eZn5eUDaHNUqHI5GdkEsAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Category = _t, Product = _t, Amount = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Amount", Int64.Type}})
in
#"Changed Type"
My question is a nephew related to its older uncle, who now I want to call in:
Percent Rank within Category =
VAR HasOneValueTrue = HASONEVALUE ( MyTable[Product] )
VAR tbl =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
REMOVEFILTERS ( MyTable[Product] ),
VALUES ( MyTable[Category] )
)
VAR result =
CALCULATE (
DIVIDE (
RANKX (
tbl,
[Sales],
,
ASC
) - 1,
COUNTROWS ( tbl ) - 1
)
)
RETURN
IF (
HasOneValueTrue,
result
)
The difference is that the uncle has Category defined in table column, but now we want to have category calculated on the fly based on sales level. So I tried
replacing the VAR tbl code with the following one with the threshold of 4:
var tbl =
SUMMARIZECOLUMNS (
MyTable[Product],
"CalculatedCategory", IF ( [Sales] > 4, "high", "low" ),
"AggSales", [Sales]
)
Nevertheless, I am not able to refer to such defined variable. I also failed with trial based on creating first a DAX table and then trying to refer to it.
Here are expected results:
References
Here is the family of related questions which members I met on the way while approaching to state this problem.
DAX equivalent of Excel PERCENTRANK.INC per category
DAX RANKX for within Category
DAX REMOVEFILTERS vs ALL
The value parameter in DAX function RANKX
DAX ALLEXCEPT to sum by category of multiple dimension tables
This can be done with a minor modification to my answer here. Copied below:
Percent Rank =
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
ALLSELECTED ( MyTable[Product] )
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE ( RankProduct - 1, COUNTROWS ( ProductsInCategory ) - 1 )
)
First, define the calculated category as you suggested.
CalculatedCategory = IF ( [Sales] > 4, "high", "low" )
Then plug that into a filter in the ProductsInCategory variable.
Exp. Results =
VAR CalculatedCategory = [CalculatedCategory] /*Determine current category*/
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = CalculatedCategory /*New Condition*/
)
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE ( RankProduct - 1, COUNTROWS ( ProductsInCategory ) - 1 )
)
Output:
Edit:
To handle the case where there is only 1 product in a category, you can use MAX to disallow a zero value for the denominator.
Exp. Results =
VAR CalculatedCategory = [CalculatedCategory] /*Determine current category*/
VAR ProductsInCategory =
CALCULATETABLE (
VALUES ( MyTable[Product] ),
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = CalculatedCategory /*New Condition*/
)
)
VAR RankProduct = RANKX ( ProductsInCategory, [Sales],, ASC )
RETURN
IF (
HASONEVALUE ( MyTable[Product] ),
DIVIDE (
RankProduct - 1,
MAX ( COUNTROWS( ProductsInCategory ) - 1, 1 )
)
)
Being very grateful to Alexis Olson, I would like to share a different solution I ended up with. The solution proposed by Alexis works well in my simple example, but it did not work in my complex model. In my complex model the RANKX function does not give the expected results. RANKX returns the same rankings for different sales values.
For the time being this is the solution that works without figuring out what causes RANKX to return ties for different sales values.
First of all, defining Category measure:
CalculatedCategory =
SWITCH (
TRUE (),
NOT ( HASONEVALUE ( MyTable[Product] ) ), "total", -- important to handle totals
[Sales] <= 4, "low",
[Sales] > 4, "high",
"other"
)
It is important to exclude totals from Category. I did it by setting up a different category for totals. Otherwise totals will fall into "high" category bucket. It would distort final results.
I have not used RANKX in calculation of Percent Rank within Category. I used MIXTURE OF COUNTROWS and FILTER.
PercentRank within Category =
VAR category = [CalculatedCategory]
VAR ProductSales = [Sales]
VAR ProductsMatching =
COUNTROWS (
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = category
&& [Sales] >= ProductSales
)
)
var ProductsAll =
COUNTROWS (
FILTER (
ALLSELECTED ( MyTable[Product] ),
[CalculatedCategory] = category
)
)
RETURN
DIVIDE (ProductsMatching-1, MAX( ProductsAll-1, 1 ))
I calculated rows of two tables. First table ProductsMatching has all products that have sales in appropriate category and sales that are higher or equal of the product. ProductsAll returns number of products in category.
I have a data structure like this
DateRoll Dataset Date Value Customer
Month Online 1/1/2018 10 Cust1
Month Online 2/1/2018 11 Cust1
Month Online 3/1/2018 12 Cust1
Month Online 4/1/2018 22 Cust1
Quarter Online 1/1/2018 33 Cust1
Quarter Online 4/1/2018 22 Cust1
I have to calculate previous quarter value, I tried different ways but it's not working
1 - Not returning any value.
CALCULATE (
SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, QUARTER ),
FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter")
)
2--Nested - Returning overall total
CALCULATE (
CALCULATE (
SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, QUARTER )
),
FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter" )
)
3--Nested --Returning overall total
CALCULATE (
CALCULATE (
SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter" )
),
DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, MONTH )
)
Tried PREVIOUSQUARTER function too, but its not returning any value.
To take advantage of built in DAX time intelligence functions you will need to to have a contiguous set of dates. I would recommend using a date table. The following code can be used to create a date/calendar table in your model:
Celndar =
Var MinDate = MIN(Data_Rollup_KPI_DNR[Date])
Var MaxDate = MAX(Data_Rollup_KPI_DNR[Date])
Var BaseCalendar = CALENDAR(MinDate, MaxDate)
RETURN
GENERATE (
BaseCalendar,
VAR BaseDate = [Date]
VAR YearDate =
YEAR ( BaseDate )
VAR MonthNumber =
MONTH ( BaseDate )
VAR YrMonth =
100 * YEAR ( BaseDate )
+ MONTH ( BaseDate )
VAR Qtr =
CONCATENATE ( "Q", CEILING ( MONTH ( BaseDate ) / 3, 1 ) )
RETURN
ROW (
"Day", BaseDate,
"Year", YearDate,
"Month Number", MonthNumber,
"Month", FORMAT ( BaseDate, "mmmm" ),
"Year Month", FORMAT ( BaseDate, "mmm yy" ),
"YrMonth", YrMonth,
"Qtr", Qtr
)
)
Once this table exists, mark it as a 'date' table and create a relationship with
Data_Rollup_KPI_DNR[Date]
Then, you can write the following measure to obtain the results you are searching for:
PQSum =
CALCULATE (
SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
PREVIOUSQUARTER ( 'Calendar'[Date] )
)
Hope that helps!
*Edited
You can also create a ranking column to index in a measure:
Rank =
RANKX (
FILTER (
'Data_Rollup_KPI_DNR',
'Data_Rollup_KPI_DNR'[DateRoll] = EARLIER ( 'Data_Rollup_KPI_DNR'[DateRoll] )
),
'Data_Rollup_KPI_DNR'[Date].[Date],
,
ASC
)
Then you can reference a previous quarter using something like the following:
PQSum2 =
CALCULATE (
SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
FILTER (
'Data_Rollup_KPI_DNR',
'Data_Rollup_KPI_DNR'[Rank]
= MAX ( 'Data_Rollup_KPI_DNR'[Rank] ) - 1
),
'Data_Rollup_KPI_DNR'[DateRoll] = "Quarter"
)
but this is hard coded and just plain nasty!
Echoing #steliok that a date dimension is the proper way to handle this; there are plenty of date table templates out there, and a date dimension will work with your data model. If you really really can't add to your data structure for some reason, this should work:
BaseValue = SUM ( 'Data_Rollup_KPI_DNR'[Value] )
PriorQuarter =
VAR CurrentDate = MAX ( 'Data_Rollup_KPI_DNR'[Date] )
VAR CurrentYear = YEAR ( CurrentDate )
VAR CurrentMonth = MONTH ( CurrentDate )
VAR FirstMonthOfCurrentQuarter =
SWITCH (
TRUE (),
CurrentMonth IN {1,2,3}, 1,
CurrentMonth IN {4,5,6}, 4,
CurrentMonth IN {7,8,9}, 7,
CurrentMonth IN {10,11,12}, 10
)
// DATE() does the right thing with negative month args
VAR PriorQuarterDate = DATE ( CurrentYear, FirstMonthOfCurrentQuarter - 3, 1 )
RETURN
CALCULATE (
[BaseValue],
ALL ( 'Data_Rollup_KPI_DNR'[DateRoll], 'Data_Rollup_KPI_DNR'[Date] ),
'Data_Rollup_KPI_DNR'[Date] = PriorQuarterDate,
'Data_Rollup_KPI_DNR'[DateRoll] = "Quarter"
)
This relies on DATE being clever, which it is. DATE ( 2019, -2, 1 ) = DATE ( 2018, 10, 1 ).
Ultimately, my question is why can't you just source the un-rolled up data from the same place that the ETL process is sourcing it?
Date functions are working well when you are using # Day level.
Following link would be helpful to resolve your issue,
https://community.powerbi.com/t5/Desktop/Lead-and-Lag-in-DAX/td-p/649162
Problem:
I need a calculated measure in DAX that sums the Value column for the last 6 sprints. I am basing the last 6 sprints on the DimSprintEndDateKey in descending order.
Table structure in PowerBI
The DAX that I am using:
CALCULATE (
SUM ( factSprint[Value] ),
FILTER (
ALL ( factSprint ),
COUNTROWS (
topn(6,
FILTER (
factSprint,
EARLIEST( RELATED ( dimSprint[DimSprintEndDateKey] ) )
> RELATED ( dimSprint[DimSprintEndDateKey] )
),RELATED ( dimSprint[DimSprintEndDateKey] ), DESC
)
)
)
)
I am assuming that the relationship on your tables is between 'dimSprint'[dimSprintKey] and 'FactSprint'[dimSprintKey].
That being the case, this measure could work for you.
Total Value Last Six Sprints =
VAR endDateSprint =
LOOKUPVALUE (
'dimSprint'[dimSprintEndDateKey],
'dimSprint'[dimSprintKey], SELECTEDVALUE ( 'FactSprint'[dimSprintKey] )
)
VAR dimTableFiltered =
FILTER ( 'dimSprint', 'dimSprint'[dimSprintEndDateKey] <= endDateSprint )
RETURN
CALCULATE (
SUM ( 'FactSprint'[Value] ),
ALL ( 'FactSprint' ),
TOPN ( 6, dimTableFiltered, [dimSprintEndDateKey], DESC )
)
Use it on a matrix visual (or pivottable). Be sure to put 'FactSprint'[dimSprintKey] or 'FactSprint'[SprintPK] on Rows and [Total Value Last Six Sprints] on Values.