Compute average (with condition) in Tableau - tableau-api

Wanted Result: Average of the turnover value on days that are between the start and end reference period.
Using Tableau Desktop
Lod expression
The first step is i return the turnover value on days that are between the start and end reference period, and return null otherwise.
Daily Turnover in reference period
IF [Date]>= [Start reference date]
and [Date]<= [End reference date]
THEN [Amount] END
Second Step is to calculate the average across this range of values for each product.
Average Turnover in reference period
{FIXED [Product]: AVG(Daily Turnover in reference period)}
Here a screen shot
The average must be 2331 and not 24.
Really i need HELP.
Thanks.

There are multiple possible approaches, here is one.
Define an LOD calc as Daily_Amount_Per_Product
{ FIXED Product, Date : SUM([Amount]) }
Put Date on the filter shelf and select the range of dates you want to analyze. Put Product on the Rows shelf and put Daily_Amount_Per_Product on the Columns shelf.
At this point you are almost, but not quite done. Since your LOD calc as at a deeper level of detail (has more dimensions in play) than your view, Tableau will perform aggregation to get a result at the same level as your view - which is why you see the word SUM before your field on the Columns shelf. If you want to see the average instead of the sum, change SUM to AVG and you should have your result.

Related

How to calculate average for the calendar year

My input file consists of column Actual Exp and Actual Min.
Now I want to create a measure for calculating the average for the current calendar year having the latest month of data for Actual Exp and Actual Min.
I want to calculate the average from Jan'21 to Mar'21, and later if data gets added for Apr or May I would like to calculate the average from Jan'21 to May'21 or Apr'21.
Similarly, I want to have from Jan '21 to Dec'21 in Dec'21 and an average from Jan'22 to Feb'22 in Feb'22. I also have a date filter I don't want my date filter to affect the average.
I tried using TOTALYTD and MAX(Date), but it's not working.
Thanks.
I've not fully understood your question, but hopefully this helps:
AVERAGEX ( ALL(TABLENAME), TABLENAME[COLUMNNAME])
This should give you an average of COLUMNNAME no matter what filters/slicing you have in place.
If you wanted to futher restrict this, you can try creating a 2nd measure such as
CALCULATE(AVERAGEX ( ALL(TABLENAME), TABLENAME[COLUMNNAME]), datetable[monthcolumn] IN {"Jan", "Feb", "Mar"})

How to aggregate table calculation in tableau

this is my workbook
on that workbook, i calculate timediff between each transaction for each users. what i build first is the filters PUL with this calculate
{Fixed [User Id]: sum(
if [Created At]<=[END_DATE] then 1 else 0 end)}>=2
AND
{FIXED [User Id]: sum(
IF [Created At]<=[END_DATE] AND
[Created At] >= [START_DATE] THEN 1 ELSE 0 END)}>=1
this formula is to find out the users who match with conditions (do transaction at least 2 before end_date parameter, and atleast doing 1 transaction in between start_date parameter and end_date parameter) after that i add to context this filters to find out the users first.
and i made filters date_range with this calculate
lookup(min(([Created At])),0) >= [START_DATE] and
lookup(min(([Created At])),0) <= [END_DATE]
so it will visualize only transaction on range (start_date as first range, and end_date as last range) and also visualize last date transaction before first range (if any).
after that i make calculate called datediff
DATEDIFF('day',LOOKUP(MIN([Created At]),-1), MIN([Created At])) and put that on label so it will calculate the day different. and also i put the date in the detail and put the date also in rows and make it ATTR.
my question is, how to find out max, min, median, and average value from this calculate
i tried with calculated max
MAX({FIXED [User Id]:DATEDIFF('day',INT(LOOKUP(MIN([Created At]),-1)), INT(MIN([Created At])))})
but it return error datediff being called with string,integer,integer
For Max and Min you can proceed like I presented you a solution on your previous question. (For max create a rank calculation and sort is descending, For Min you create a second rank calculation ordered ascending).
However, as far as my knowledge of table calculations in tableau goes, Tableau doesn't allow to hard-code these table calculated fields and therefore you cannot-
further aggregate these results
perform LOD calculations on these.
For calculation of these like average and median, It is advised that you may please create a hard-coded column/field which give you the time-difference on any order with that customer's previous order. This you can do it in any programming language of your choice like R or python (or other).
Moreover, Tableau integration with R/python is through script-real type functions which are again of table calculation category and above restrictions will apply.
Good Luck.
EDIT as Alex Blakemore has suggested on a different question/answer, you can use window functions with a slight tweak. Let's assume your calculated field name for datediff is [CF], then create four calculated fields with the following calculations.
window_max([CF])
window_min([CF])
window_avg([CF])
window_median([CF])
and name them [CF max], [CF Min], [CF avg], [CF Median] respectively.
Now edit table calculation with nesting in each four these, as follows-
click nested calculations down arrow. CF will be listed there. change its calculation to specific dimensions, at level deepest and restarting at evrey user id. the screenshot is
thereafter click nested calculations down arrow again. select CF_max/min/med/avg (as the case may be) and create table calculations with table down.
You'll get a view like this as desired.

Execute IF-THEN_ELSE before Execute Calculation - Tableau

I have a graph below.
I would like to calculate lapsed rate which is sum of lapsed value divided by sum of inforce value. I use the formula below in calculated field.
abs(sum(if[Status]='lapsed'then[TotalAmount]end))/abs(sum(if[Status]='inforce'then[TotalAmount]end))
However that formula will also pick the value from Q2 (quarter 2) 2016. What I want to do is to tell tableau to check first if any quarter does not contain both inforce value and lapsed value then skip that quarter. In this case I need to calculate lapsed rate which does not include Q2 2016. How do i do this?
I'm using Tableau v.10.
Thanks.
This is just a quick approach and may not be the most efficient but it seems to work.
You need to use a combination of a row level calculation and a level of detail calculation.
The level of detail calculation can be used to flag the quarters which have both a lapsed and inforced status. Once these quarters are flagged you can calculate the lapsed rate at a row level which can then be rolled up using a sum.
Create a calculated field as follows:
Let me know if you have any questions or need any tweaks.
if
avg(
// Calculate the number of Inforce/Lapsed occurences per Quarter
IF
[Status] = 'Inforce'
or
[Status] = 'Lapsed'
then
{ FIXED
DATEPART('quarter', [Date]):
countd([Status])
}
else
0
end)
//
= 2
then
// Calculate the Lapsed Rate as both statuses exist in the quarter
sum((if
[Status] = 'Lapsed'
then [Total Amount]
END))
/
sum([Total Amount])
END

Pick group totals, grand totals and normal summarization in Tableau

I am trying to calculate average of 2 columns in another column in Tableau but difficult part is grand total is not getting average instead it is the sum of 3rd calculated field.
A B Calculated field
10 5 2
6 3 2
T 16 8 4 (Here I should get 2 instead it is taking sum of column)
Here I am unable to write separate formula for row totals and grand totals, Only one formula (Calculated Field) is allowed and when I am dragging on sheet it is by default aggregating to sum.
Note: I am expert in Crystal and BO but beginner in Tableau.
Update
Code used for LoD
{FIXED [Product Category]: AVG([Sales])}
Below image is what I got after implementation I have tried with 2 columns but the result is same if I use only one column (I am trying to get the average of sales)
You are almost there - the Grand Total by default does a SUM function you just have use the Total All Using --> Average option.
Output : Level wise SUM(Profit) later averaged across columns and rows. (Show Column Grand Total & Show Row Grand Total active)
Update: Answering the question below. To get the Row-wise avg (which is Cat1-vag in this case) you could just drop the measure and change it to AVG(). Since you needed in a Calculated Field you could use a Simple FIXED LOD. You can also uncheck aggregated measures from Analysis dropdown and have no Dimension in column or row like unlike what this example shows and still get three different averages. Cheers.
{FIXED [Cat1]:AVG([Profit])}
Check out this very smart work around from Joe Mako.
https://community.tableau.com/thread/112791
create a calc field like:
IF FIRST()==0 THEN
WINDOW_AVG(SUM([Sales]),0,IIF(FIRST()==0,LAST(),0))
END
duplicate your Category field
place "Category (copy)" on the level of detail
set the compute using for the calc field pill to use "Category (copy)"
The window function in the calculated field only takes into account what's in the view, and aggregate based on those number.

How to Calculate YTD (Jan to prev month) in a single column in tableau

Original post - https://community.tableau.com/thread/206909
I have a report in which I have sales per month in the column and commodities in the row. The data show actual sales and future estimates for each month.
Need to calculate Year-To-Date (YTD) total for 2016 (from Jan to Previous month) and have it in a single column at the end of the actual values.
I already created a calculated field - YTD
IF
YEAR([DATE]) = YEAR(NOW())
AND
MONTH([DATE])< MONTH(NOW())
THEN
[VALUE/UNIT]
ELSE
0
END
But when I add to the view, it creates a another section for YTD with sum for each month till April.
Can someone please help me in how to achieve this in Tableau?
There are couple of ways to achieve this view in Tableau
1. To create calculated field for each Month and YTD and add measure names in Row & Measure values in Text
2. Make union of 2 queries - one that select all the correct values & second that have YTD calculation in month column. Then use pivot it