High Value at Each Granularity - tableau-api

I have an table below which shows some data and I am trying to get the high value from each row.
Below is the data I have:
Table A
Once calculated it should looks like below in tableau
Table B
Notice that for Total, its not summing up from pers and bus instead its getting it highest value from total from table A and same concept is for Grand Total. Numbers which you see are balance.
I am able to get high value up to Total but its the grand total where I am struggling with. Below is my Calculation which I am using.
if
countd([Category]) = 1 then
sum({ FIXED [Group], [Category]: max(
{ FIXED [Group], [Category], [Date]: SUM([Balance])})})
ELSE
sum({ FIXED [Group]: max(
{ FIXED [Group], [Date]: SUM([Balance])})}
)
END

Step-1: For max of categories, use this calculation desired maximums
MAX({Fixed [MVRA Group], [Product Category], [Date Display]: ([Primary Measure])})
STEP-2: For max of subtotal, use desired sub-total maximum
MAX({Fixed [MVRA Group], [Date Display]: ([Primary Measure])})
https://drive.google.com/file/d/1zyjCDdG_QECrkFgY-UFm7WM2yN1xaHmZ/view?usp=sharing

Related

Calculating sum with no direct join column

I have a table (ShipJourneys) where I need to calculate the Total Fuel Consumed which is a float value. See the image below.
This value is obtained by summing all the individual consumers of fuel for a given vessel over the timeframe specified. This data is contained in a second table.
Boxed in area in red shows there were 5 fuel consumers (specified by the FK_RmaDataSumsystemConfigID) and that 3 of the consumers had burned 0 units of fuel and 2 had each burned 29.
To calculate the totalFuelConsumed for that range of time frames, for a given vessel (stipulated by the FK_RmaID), the following query could be used
Select sum(FuelCalc)
from FuelCalc
where Timestamp >= '2019-07-24 00:00:00'
and Timestamp <= '2019-07-24 00:02:00'
and FK_RmaID = 660
Using something like the query below does not work, resulting in bogus values
UPDATE ShipJourneys
SET TotalFuelConsumed =
(Select sum(FuelCalc) from FuelCalc as f
WHERE f.timestamp >= StartTimeUTC
and f.timestamp <= EndTimeUTC
and f.FK_RmaID = FK_RmaID)
Any suggestions on how I could join them
You could try something like that:
UPDATE myTable // Put the table correct name here
SET TotalFuelConsumed =
Select sum(FuelUsed) from FuelTimeTbl as fuelTbl
WHERE fuelTbl.timestamp >= '2019-10-21 22:13:55.000'
and fuelTbl.imestamp <= '2019-11-27 17:10:58.000'
and fuelTbl.FK_RmaID = myTable.RmaID // Put the correct attribute name

Calculate median sales price with using 3 variables Tableau 10

I would like calculate the median sales price and the median rental price for an apartment in NYC in each of the 5 boroughs, Brooklyn, Bronx Manhattan, Queens and Staten Island. In Tableau the sales and and rentals are groups of ListPrice -- Variables ListPrice is NUMBER(decimal) Type (includes Sales & Rentals, Borough
Any help is appreciated
I tried using Tableau's table calculation feature but that did not work, I tried
WINDOW_MEDIAN(SUM([ListPrice])-1, -1)
ERROR: WINDOW_MEDIAN is being called with (float, integer), did mean
(float,integer,integer)
Data
Type Borough ListPrice
RentalType1 Manhattan $5,000
RentalType2 Bronx $3,000
RentalType2 Brooklyn $3,000
SalesType2 Manhattan $900,000
SalesType1 Brooklyn $100,000
SalesType1 Bronx $500,000
SalesType2 Queens $800,000
SalesType2 Staten Island $400,000
Table calculations takes 3 arguments, Expression, First row of the partition and last row of the partition. In your formula you haven't given last row of the partition.
Run the function for type in each Borough and calculate for each Borough.
So your formula would be:
WINDOW_MEDIAN(SUM(INT([List Price])),FIRST(),LAST())
are you looking to get values below:
Here calculation2 is median value

how to get min or max date on columns in mdx query

what mdx query logic could i implement for this example to get two rows in result set for hrid = 1 with 1/1/16 as min date(start) for first row where someattribut shows up on column with value 'A'
and 1/15/16 as min date(start) for second row where someattribute has value of 'B' and measure.whatevers has its aggregation for whatever data corresponds to that dimension row.
Im trying to just look at january 2016
everything ive tried i seem to get min date values of 1/1/1900 or both rows have value of 1/1/2016 or i get errors since i cant figure it out.
heres my mdx sample:
WITH MEMBER [Measures].[Start] as
(
-- min date that the combination of someattribute and hrid have certain
-- value withing the range of the where clause restriction of january 2016
SELECT {
[Measures].[Start]
, [Measures].[Whatevers]
} ON COLUMNS
, NON EMPTY {
[Agent].[HRID].children
* [Agent].[someAtribute].Members
} ON ROWS
FROM [RADM_REPORTING]
WHERE (
[Date].[Date View].[Month].&[201601]
)
this works, but it feels kind of like a hack or maybe it feels like its not robust, I am not familiar enough with mdx to be able to make that call.
WITH MEMBER [Measures].[Start] as
filter([Date].[Date View].[Month].&[201601].children,
[Measures].[Whatevers]).item(0).membervalue
Here is a potential direction that is more general:
WITH
MEMBER [Measures].[Start] AS
Min
(
(EXISTING
[Date].[Date].[Date].MEMBERS)
,IIF
(
[Measures].[Internet Sales Amount] = 0
,NULL
,[Date].[Date].CurrentMember.MemberValue
)
)
SELECT
NON EMPTY
{
[Measures].[Start]
,[Measures].[Internet Sales Amount]
} ON COLUMNS
,NON EMPTY
[Product].[Product Categories].[Product] ON ROWS
FROM [Adventure Works]
WHERE
[Date].[Calendar].[Calendar Year].&[2005];
It gives the following:

Tableau - Calculating average where date is less than value from another data source

I am trying to calculate the average of a column in Tableau, except the problem is I am trying to use a single date value (based on filter) from another data source to only calculate the average where the exam date is <= the filtered date value from the other source.
Note: Parameters will not work for me here, since new date values are being added constantly to the set.
I have tried many different approaches, but the simplest was trying to use a calculated field that pulls in the filtered exam date from the other data source.
It successfully can pull the filtered date, but the formula does not work as expected. 2 versions of the calculation are below:
IF DATE(ATTR([Exam Date])) <= DATE(ATTR([Averages (Tableau Test Scores)].[Updated])) THEN AVG([Raw Score]) END
IF DATEDIFF('day', DATE(ATTR([Exam Date])), DATE(ATTR([Averages (Tableau Test Scores)].[Updated]))) > 1 THEN AVG([Raw Score]) END
Basically, I am looking for the equivalent of this in SQL Server:
SELECT AVG([Raw Score]) WHERE ExamDate <= (Filtered Exam Date)
Below a workbook that shows an example of what I am trying to accomplish. Currently it returns all blanks, likely due to the many-to-one comparison I am trying to use in my calculation.
Any feedback is greatly appreciated!
Tableau Test Exam Workbook
I was able to solve this by using Custom SQL to join the tables together and calculate the average based on my conditions, to get the column results I wanted.
Would still be great to have this ability directly in Tableau, but whatever gets the job done.
Edit:
SELECT
[AcademicYear]
,[Discipline]
--Get the number of student takers
,COUNT([Id]) AS [Students (N)]
--Get the average of the Raw Score
,CAST(AVG(RawScore) AS DECIMAL(10,2)) AS [School Mean]
--Get the number of failures based on an "adjusted score" column
,COUNT([AdjustedScore] < 70 THEN 1 END) AS [School Failures]
--This is the column used as the cutoff point for including scores
,[Average_Update].[Updated]
FROM [dbo].[Average] [Average]
FULL OUTER JOIN [dbo].[Average_Update] [Average_Update] ON ([Average_Update].[Id] = [Average].UpdateDateId)
--The meat of joining data for accurate calculations
FULL OUTER JOIN (
SELECT DISTINCT S.[Id], S.[LastName], S.[FirstName], S.[ExamDate], S.[RawScoreStandard], S.[RawScorePercent], S.[AdjustedScore], S.[Subject], P.[Id] AS PeriodId
FROM [StudentScore] S
FULL OUTER JOIN
(
--Get only the 1st attempt
SELECT DISTINCT [NBOMEId], S2.[Subject], MIN([ExamDate]) AS ExamDate
FROM [StudentScore] S2
GROUP BY [NBOMEId],S2.[Subject]
) B
ON S.[NBOMEId] = B.[NBOMEId] AND S.[Subject] = B.[Subject] AND S.[ExamDate] = B.[ExamDate]
--Group in "Exam Periods" based on the list of periods w/ start & end dates in another table.
FULL OUTER JOIN [ExamPeriod] P
ON S.[ExamDate] = P.PeriodStart AND S.[ExamDate] <= P.PeriodEnd
WHERE S.[Subject] = B.[Subject]
GROUP BY P.[Id], S.[Subject], S.[ExamDate], S.[RawScoreStandard], S.[RawScorePercent], S.[AdjustedScore], S.[NBOMEId], S.[NBOMELastName], S.[NBOMEFirstName], S.[SecondYrTake]) [StudentScore]
ON
([StudentScore].PeriodId = [Average_Update].ExamPeriodId
AND [StudentScore].Subject = [Average].Subject
AND [StudentScore].[ExamDate] <= [Average_Update].[Updated])
--End meat
--Joins to pull in relevant data for normalized tables
FULL OUTER JOIN [dbo].[Student] [Student] ON ([StudentScore].[NBOMEId] = [Student].[NBOMEId])
INNER JOIN [dbo].[ExamPeriod] [ExamPeriod] ON ([Average_Update].ExamPeriodId = [ExamPeriod].[Id])
INNER JOIN [dbo].[AcademicYear] [AcademicYear] ON ([ExamPeriod].[AcademicYearId] = [AcademicYear].[Id])
--This will pull only the latest update entry for every academic year.
WHERE [Updated] IN (
SELECT DISTINCT MAX([Updated]) AS MaxDate
FROM [Average_Update]
GROUP BY[ExamPeriodId])
GROUP BY [AcademicYear].[AcademicYearText], [Average].[Subject], [Average_Update].[Updated],
ORDER BY [AcademicYear].[AcademicYearText], [Average_Update].[Updated], [Average].[Subject]
I couldn't download your file to test with your data, but try reversing the order of taking the average ie
average(IF DATE(ATTR([Exam Date])) <= DATE(ATTR([Averages (Tableau Test Scores)].[Updated]) then [Raw Score]) END)
as written, I believe you'll be averaging the data before returning it from the if statement, whereas you want to return the data, then average it.

MDX How to add bands to grouped fact table

I'm trying to create income bands on my fact table.
The fact table that consists of
Date, TranType, AdvKey, Amount
01/01/2015 TRAN1 ID01 5000
01/02/2015 TRAN1 ID02 13000
01/03/2015 TRAN2 ID01 500
The AdvKey links back to DimIFADetails, this table has a ParentKey, a Parent Child hierarchy. There are two levels, Adviser and Adviser Group
ADVKEY PARENTKEY
----------------
ID01 ID03
ID02 ID03
ID03 NULL
I want to be able to group on AdvKey or AdvGrpKey and have the summed amounts (income) allocated to income bands.
So when I group on Adviser, each adviser will be assigned an income band, ie 0-10k, 10-50k, 50-100k, same applies when the grouping is changed to the Group Level.
In the above
ID01 5300 0-10000
ID02 13000 10000-20000
or if by Adviser Group
ID03 18300 10000-20000
In SQL, I could group by the key necessary, then add a column and case statement to allocate each aggregated amount to a band.
The facttable has about 2 million rows.
The income is how much is generated from the advisers and adviser group, so this will change over time.
I can't think of any way to do it with a dimension, as there is no way to link back to the fact table seeing as these are groupings done at run time.
I now have something that works
with
MEMBER Measures.[Calc Sum] as
IIF( Sum(EXISTING [Dim IFA Details].[Parent Key].[Adviser Group].Members,
Measures.[Amount] * -1
) <= 10000 , '0-10000', IIF( Sum(EXISTING [Dim IFA Details].[Parent Key].[Adviser Group].Members,
Measures.[Amount] * -1
) <= 20000 , '10001 - 20000' , '>20000' ))
SELECT { [Measures].[Amount] , measures.[Calc Sum] }
ON COLUMNS,
NONEMPTY( [Dim IFA Details].[Parent Key].[Adviser Group].Members , [Measures].[Amount])
on rows
FROM [Income and Emails Cube]
Its going to have a rather bulky IIF when I add more bands.
Is it possible to create a dimension with the categories and add the keys on the fly like this?
or would there be no benefit.