DAX Proportion of balance by state and date - ssas

I am currently attempting to use DAX queries to calculate the proportion of the balance attributed to each State in my analysis cube, from the following image:
I currently have a Sales table with a ReportDateKey that joins a ReportDate table that has a DateKey
If I use the following statement:
AllCurrentBalanceByDate:=CALCULATE([TotalCurrentBalance],ALLSELECTED())
It gives me the overall total, ignoring the date altogether, which is a useless figure.
If I enter the following query and display it in the excel spreadsheet:
AllCurrentBalanceByDate:=CALCULATE([TotalCurrentBalance],ALLSELECTED('Report Date'[Month]))
it is returning the same data as found in the Balance column. Again, useless. I need a total for each month, so that I can calculate the state balance / overall total for that month to get the proportion/percentage attributable to that State.
What am I doing wrong?

So if you want your measure to ignore whichever State is selected, you need to include the State columns in your ALL filter.
Also I suppose you want to use ALL instead of ALLSELECTED as your overall balance per month shouldn't be affected by external filters on state (but this depends on your use case)?
AllCurrentBalanceByDate:=CALCULATE(SUM([CurrentBalance]),ALL(Geography[StateName]))

Related

How to right click table to show values?

In a pivot table that plots values against a timeline it is possible to right-click the table, select "Show values as..." and have them appear as a percentage of a particular day.
I'm trying to recreate the same behaviour using DAX measures: I would like to have a measure that shows each day's price as a percentage of the first day of the year.
I've successfully created a measure that correctly identifies the first date of the year, i.e. the baseline:
FDate:=CALCULATE(FIRSTDATE(Prices[Date]),ALLEXCEPT('Calendar','Calendar'[Year]))
However, I can't figure out how to use this FDate to get that day's price (needed as the baseline for further calculations):
CALCULATE([Sum of Price], ALLEXCEPT('Calendar','Calendar'[Year]), FILTER('Prices', 'Prices'[Date]=[FDate])) returns each day's price, not the first date's.
CALCULATE([Sum of Price], FILTER(ALLEXCEPT('Calendar','Calendar'[Year]),'Calendar'[Date]=[FDate])) ignores the YEAR report filter and returns the price of the very first date in my calendar table and not the first date in the year I've filtered for.
Any pointer in the right direction would be greatly appreciated!
Thanks
Here's the solution:
VAR FirstDate = [FDate]
RETURN(
CALCULATE([Price],
FILTER(ALLEXCEPT('Calendar','Calendar'[Year]),'Calendar'[Date]=FirstDate))
)
Variables allow you to define measure in a certain filter context but to leave it unaffected by subsequent filter contexts - that at least is my layman's understanding.
More info here: https://www.sqlbi.com/articles/variables-in-dax/

Query to find average stock ... with a twist

We are trying to calculate average stock from a movements table in a single sql sentence.
As far as we are, no problem with what we thought was a standard approach, instead of adding up the daily stock and divide by the number of days, as we don’t have daily stock, we simply add (movements*remaining days) :
select sum(quantity*(END_DATE-move_date))/(END_DATE-START_DATE)
from move_table
where move_date<=END_DATE
This is a simplified example, in real life we already take care of the initial stock at the starting date. Let’s say there are no movements prior to start_date.
Quantity sign depends on move type (sale, purchase, inventory, etc).
Of course this is done grouping by product, warehouse, ... but you get the idea.
It works as expected and the calculus is fine.
But (there is always a “but”), our customer doesn’t like accounting days when there is no stock (all stock sold out). So, he doesnt like
Sum of (daily_stock) / number_of_days (which is what we calculate using a diferent math)
Instead, he would like
Sum of (daily stock) / number_of_days_in_which_stock_is_not_zero
For sure we can do this in any programming language without much effort, but I was wondering how to do it using plain sql ... and wasn’t able to come up with a solution.
Any suggestion?
Consider creating a new table called something like Stock_EndOfDay_History that has the following columns.
stock#
date
stock_count_eod
This table would get a new row for each stock item at the start of a new day for the prior day. Rows could then be purged from this table once the applicable date value went outside the date window of interest.
To get the "number_of_days_in_which_stock_is_not_zero", use this.
SELECT COUNT(*) AS 'Not_Zero_Stock_Days' FROM Stock_EndOfDay_History
WHERE stock# = <stock#_value>
AND <date_window_clause>
Other approaches might attempt to just add a new column to the existing stock table to maintain a cumulative sum of the " number_of_days_in_which_stock_is_not_zero". But inevitably, questions will be asked as to how did the non-zero stock days count get calculated? Using this new table approach will address those questions better than the new column approach.

Need to perform some not so straight forward data processing in Access 2010

I have a table in Access that is setup like the one in the photo. What I need to do is this:
For each part no, I want to sum the total Qty for each month and type (Ordered and Demand). Then I need to cap the qty in the rows where the type is = to Orders to the value of the Qty where the type is = to Orders, when the sum of the Qty for Ordered is greater than Demand. Let me try to explain it another way.
I want to look at a subset of the master data, in this case the subset is by part no (rows with identical part numbers). For this subset I want to have two sets of sums. 1. The sum of qty with type = Ordered AND 2. a sum of qty with type = Demand. If the sum for Ordered is greater than demand, I want to change the Qty for Ordered to be the value of the Qty for Demand.
Essentially, the business reason is that for reporting purposes the total Qty for Ordered shouldn't be more than Demand in a given month, for a part number.
Looking at the photo, the rows in red will need to change because the sum of the qty is 30, which is greater than the sum of qty for the green rows (25). The red rows qty should be changed to 20 and 5 to match the green rows.
Whew, hope this made sense because it is hard to explain. I have tried many things for a couple weeks now, and I am a bit fuzzy on the details so I will just give a high level. Ok so what have I tried:
I have tried to join the table to iself, using part no (and date I believe) to join on, but that doesn't work because the sum would somehow be incorrect sometimes.
Pivot the table, using the transform and pivot functions in Access but it's important for me to keep the individual dates in tact and when I pivoted it I had to roll it up on a month basis. This gives me the row structure I need to make the changes but I don't know how to get back the original date format after I am done.
I am guessing I need some VBA code that loops through each part no, but I am not big on VBA code and I don't have much time to learn it. Any suggestions? I know this is long winded but its a complicated problem (at least for me). Thanks in advance.

Filter PowerPivot based on multiple Date Criteria

I am trying to apply some Time Intelligence functions in my PowerPivot workbook concerning projects and money received for them. I have three relevant tables; Matters, Payments, and a Date Table.
Each matter has a creationDate, and a closureDate(from a linked table). Likewise, each payment has a date. I have reporting set up decently, but am now trying to use Time intelligence to filter this a bit more clearly.
How can I set a PowerPivot Pivot Table up so that the only Matters which show are those which existed within the period selected. e.g. If I select a slicer for 2014, I don't want to show a matter created in 2015, or one which was closed in 2013. The matter should have been active during the period specified.
Is this possible?
You want to show all the matters EXCEPT those where the CreationDate is after the upper limit of the date range you are looking at or the ClosureDate is before the lower limit of the date range you are looking at.
Assuming you have a data structure like this, where the left-hand table is the Matters and the right-hand one is the Payments:
If you have a calculated field called [Total Payments] that just adds up all the payments in the Payments table, a formula similar to this would work:-
[Payment in Range]:=IF(OR(MIN(Matters[Creation Date])>MAX('Reporting Dates'[Date]),MAX(Matters[Closure Date])<MIN('Reporting Dates'[Date])),BLANK(),[Total Payments])
Here is the result with one month selected in the timeline:
Or with one year selected in the year slicer:
NOTE: in my example, I have used a disconnected date table.
Also, you will see that the Grand Total adds up all the payments because it takes the lowest of all the creation dates and the highest of all the closure dates to determine whether to show a total payment value. If it is important that the Grand Total shows correctly, then an additional measure is required:
[Fixed Totals Payment in Range]:=IF(COUNTROWS(VALUES(Matters[Matter]))=1,[Payment in Range],SUMX(VALUES(Matters[Matter]),[Payment in Range]))
Replace the [Payment in Range] in your pivot table with this new measure and the totals will show correctly, however, this will only work if Matters[Matter] is used as one of the fields in the pivot table.
Use filters & the calculate function.
So, if you're Summing payments, it would look like.....
Payments 2014:= CALCULATE( SUM([Payments]), DateTable[Year]=2014)
The Sum function takes the entirety of payments & the filter function will only capture payments w/in 2014, based on the data connected to your date table.

How do I compute an average of calculated averages in MS reportviewer/rdlc?

I've searched here and elsewhere on the web and have not found this exact problem/solution.
I'm building an rdlc report using the MS reportViewer - the report I'm creating is based on an existing spreadsheet where the average price across 6 months is calculated individually for each month, then the average of those prices is calculated as the 6 month period average price. Whether I agree with that methodology or if it's correct is irrelevant, I just need to know how to get an rdlc to do this.
For example:
Month Price1 Price2 Delta
May-12 $31.54 $30.03 $1.51
Jun-12 $36.27 $34.60 $1.67
Jul-12 $44.19 $42.00 $2.19
Aug-12 $38.96 $37.06 $1.90
Sep-12 $36.89 $35.08 $1.81
Oct-12 $35.57 $33.97 $1.60
Average $37.24 $35.46 $1.78
(sorry for the lack of a screen snip, I'm new and the system won't let me post an image...)
I've created a tablix that does the monthly averages computation - I use a group in the table to group the 6 months of data by month (and then hide the hourly price data so you only see the month total row) but I'm stuck on how to calculate the bottom row of the table which is the average of each column. (the average of the averages is not the same as the average of all 6 months of prices from the underlying data - that's what I've learned in this process... IOW, that was my first solution :-) )
What I tried to do to get the average of the averages was give the month total cell a name, MonthlyAvgPrice1, then in the bottom row, used this expression:
Avg(reportitems!MonthlyAvgPrice1.Value)
As I kind of expected, this didn't work, when I try to run the report, it gets a build error saying "The Value expression for the textrun 'Price1PeriodAvg.Paragraphs[0].TextRuns[0]' uses an aggregate function on a report item. Aggregate functions can be used only on report items contained in page headers and footers."
Hopfully I've explained this well, does anyone know how to do this?
Thanks!
-JayG
Actually it is not clear from the question that how are you in particular binding the data to the report items, But from the given information what I understand is that you can
Try like this:
Right Click the tablix row and insert a row below
In the cell where you want to have this Average of Averages insert the following expression
=Sum(Fields!Price1.Value)/6
and similarly insert expression =Sum(Fields!Price2.Value)/6 and =Sum(Fields!Delta.Value)/6 in the other cells where you want to display the Averages
Of Course, you will change the Field names Price1,Price2 etc to the fields that you are getting the values from.
HTH