Execute IF-THEN_ELSE before Execute Calculation - Tableau - tableau-api

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

Related

How to calculate total count of previous year

I have student data classified as per the year of enrollment and semester. For calculating retention rate, I need to divide all retained students for CY by total count of PY. How should I create a formula for that?
Your code will look something like this
Calc 1
IF Year = 2021 THEN Amount END
Calc 2
IF Year = 2020 THEN Amount END
Then you do Calc 1 - Calc 2 in another calculated field. Or you can also use lookup function if it is a table calculation
Lookup Function -1

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.

how to separate weekday/weekend calculation in tableau?

i know someone has probably asked this but i can't seem to find an answer that works for me.
i have an excel sheet that contains the sales and dates of a company.
i want to calculate the average of the sales made during weekday/weekend receptively, and use that average to calculate any outliers such as a sudden drop increase/decrease in sales.
i have created a calculation to identify between weekday/weekend
IF
DATENAME('weekday', [Date]) = "Saturday"
OR DATENAME('weekday', [Date]) = "Sunday"
THEN "Weekend"
Day Calculation
i have also created a calculation that calculates the average
INT(SUM(
IF [Day] = 'Weekday'
THEN [Number of Records]/22
ELSE
[Number of Records]/8
END ))
Average Calculation
this is my calculation to calculate outliers 20% higher/below the average
[Number of Records] * 1.2 > [Average]
OR
[Number of Records] * 0.8 < [Average]
Outlier Calculation
but it doesn't seem to be working when i put the outlier calculation into "color". the bar chart remains the same
Bar Chart
how do i go about resolving this? is my calculations wrong?
In your graph, the average is calculated at the level of date, for that reason is not working (is always true). To fix this, you have to use Level of Details expressions.
Also, considering you want to calculate the average of the sales made during weekday/weekend, your calculations should use the measure Sales instead Number of Records.
The average calculation would look like this:
{FIXED [Day]: AVG([Sales])}
And the outlier calculation:
[Sales] > 1.2 * [Average] OR [Sales] < 0.8 * [Average]

Compute average (with condition) in Tableau

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.

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