How to get missing previous quarter data - excel

I'm having two different tables Finance and Budgets. There is a relationship between two tables.
Finance Table:
As of Date
Property Id
YTD Revenue
Quarter
3/31/21
1
$5,000
1
6/30/21
1
$6,000
2
3/31/21
2
$7,000
1
6/30/21
2
$8,000
2
Budgets:
As of Date
Property Id
Budget Revenue
Quarter
3/31/21
1
$10,000
1
6/30/21
1
$10,000
2
3/31/21
2
$11,000
1
The business doesn't want to enter the data if the Budget Revenue is same as the last quarter.
There is a quarter slicer on the page and I'm using Finance[Quarter]. Let's say I'm selecting 2nd quarter and there is no quarter 2 data for the property id 2 on the Budgets table and in this case we have to show Budget Revenue from last quarter i.e 3/31/2021($11,000).

Create a new Budget table.
Combine the two tables using JoinKind.FullOuter with all the columns except Revenue as the key
Expand the Budget Revenue column of the resultant table
Fill Down the Budget Revenue column
delete the unneeded columns and re-order the columns
let
Source = Table.NestedJoin(
Revenue, {"As of Date", "Property Id", "Quarter"},
Budget, {"As of Date", "Property Id", "Quarter"}, "Budget",
JoinKind.FullOuter),
#"Expanded Budget" = Table.ExpandTableColumn(Source, "Budget", {"Budget Revenue"}, {"Budget Revenue"}),
#"Filled Down" = Table.FillDown(#"Expanded Budget",{"Budget Revenue"}),
#"Removed Columns" = Table.RemoveColumns(#"Filled Down",{"YTD Revenue"}),
#"Reordered Columns" = Table.ReorderColumns(#"Removed Columns",{"As of Date", "Budget Revenue", "Quarter"})
in
#"Reordered Columns"

Related

Power Pivot - how to unpivot multiple colums, common months

I have some data in the following format
Item
Spend Month 1
Spend Month 2
Income Month 1
Income Month 2
First
row
Number
Number
Number
Second
row
Number
Number
Number
I would like to trans form this to
Item
Month
Spend
Income
First
Month 1
Number
Number
First
Month 2
Number
Number
Second
Month 1
Number
Number
Second
Month 2
Number
Number
Here is one possible solution in PowerQuery:
let
Quelle = Excel.CurrentWorkbook(){[Name="Tabelle1"]}[Content],
UnpivotOtherColumns = Table.UnpivotOtherColumns(Quelle, {"Item"}, "Month", "Wert"),
DuplicateColumn = Table.DuplicateColumn(UnpivotOtherColumns, "Month", "Attribute"),
TextAfterDelim = Table.TransformColumns(DuplicateColumn, {{"Month", each Text.AfterDelimiter(_, " ", {1, RelativePosition.FromEnd}), type text}}),
TextBeforeDelim = Table.TransformColumns(TextAfterDelim, {{"Attribute", each Text.BeforeDelimiter(_, " "), type text}}),
PivotColumn = Table.Pivot(TextBeforeDelim, List.Distinct(TextBeforeDelim[Attribute]), "Attribute", "Wert")
in
PivotColumn

Using Power query to group patient visits within a date range

I have a list of patients with visit effective from dates that fall within the effective dates of their initial visits that i don't need to bill. The effective dates start on the date of admission and end 30 days from the date of discharge. Since most patients are discharged the same day the common effective date rand is 30 days but can be more.
Patient
Visit start date
discharge + 29 days
Number of visits
Bill / Don't Bill
John
1/7/2021
2/5/2021
4
Bill
John
1/13/2021
2/11/2021
4
Don't Bill
John
2/11/2021
3/12/2021
4
Bill
John
2/18/2021
3/19/2021
4
Don't Bill
Jane
4/19/2021
5/18/2021
4
Bill
Jane
9/8/2021
10/7/2021
4
Bill
Jane
9/10/2021
10/9/2021
4
Don't Bill
Jane
9/18/2021
10/17/2021
4
Don't Bill
Joe
1/9/2021
2/7/2021
2
Bill
Joe
1/14/2021
2/12/2021
2
Don't Bill
I was hoping to find a function that can grab the initial date range based on the minimum of the "visit start date" column for each patient. In the image above the initial visit is marked "bill" and the initial date range is set to 1/7/2021-2/5/2021. Since John's 2nd visit has a visit start date that falls within the initial range it id marked don't bill. it does not matter that the discharge date is out of the range as long as the start date is within. John's 3rd visit has a visit start date outside the previous date range so it should be billed and set as the new date range. I hope this makes sense :(
enter image description here
Using PowerQuery (data ... from table/range .... )
The main trick is to sort on patient, then start date, and then offset the data one row so you can compare to what is in there already to see if it falls into the range of the prior row
Sample code and data, that you could paste into home... advanced editor...
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Patient", type text}, {"Visit start date", type date}}),
#"Sorted Rows" = Table.Sort(#"Changed Type",{{"Patient", Order.Ascending}, {"Visit start date", Order.Ascending}}),
//copy down all the columns, offset by one row
MinusOne = #table({"Column1"}, {{null}}) & Table.Skip(Table.DemoteHeaders(Table.RemoveLastN(#"Sorted Rows",1)),1),
custom1 = Table.ToColumns(#"Sorted Rows") & Table.ToColumns(MinusOne ),
custom2 = Table.FromColumns(custom1,Table.ColumnNames(#"Sorted Rows")&Table.ColumnNames(MinusOne ) ),
//start using them
#"Added Custom1" = Table.AddColumn(custom2, "Custom", each if [Column2]=null then [Visit start date] else if [Patient]=[Column1] and [Visit start date]>=[Column2] and [Visit start date]<=Date.AddDays([Column2],28) then [Column2] else [Visit start date]),
#"Added Custom" = Table.AddColumn(#"Added Custom1", "Bill / Dont Bill", each if [Visit start date]=[Custom] then "Bill" else "Don't Bill"),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Column1", "Column2", "Custom"})
in #"Removed Columns"
If you need the bill end date, just add column .. custom column .. with formula =Date.Add([Visit Start Date],28)

Find and append dates in multiple columns based on a date range

I'm looking for a way to find dates in multiple columns that fall within the past week and output those dates. Goal is to make it expandable through many more columns.
We will assume the week is 1-Sep through 7-Sep
EX:
Name
Box 1
Box 2
Bill
1-Sep-21
3-Sep-21
Bob
30-Aug-21
3-Sep-21
Jeff
31-Aug-21
4-Sep-21
Sam
31-Aug-21
29-Aug-21
Output
Name
Item Sold
Date
Bill
Box 1
1-Sep-21
Bill
Box 2
3-Sep-21
Bob
Box 2
3-Sep-21
Jeff
Box 2
4-Sep-21
My first thought would be to unpivot the date columns using Power Query and then apply a date filter to the result.
The coding in the advanced query editor would look something like:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Name"}, "Attribute", "Value"),
#"Filtered Rows" = Table.SelectRows(#"Unpivoted Other Columns", each [Value] >= #datetime(2021, 9, 1, 0, 0, 0) and [Value] <= #datetime(2021, 9, 7, 0, 0, 0))
in
#"Filtered Rows"
By using unpivot other columns, you'd be able to add as many date columns to the original table as you like.

How can I calculate something which has other rows as inputs in power query?

I have a table in Power query, which besides other fields has the following key fields:
SKU | Year | Week | Customer | Transaction | Type | Value
As an example, some rows would be:
AB587 | 2019 | 12 | Tom | Purchase | Forecast |200
AB587 | 2019 | 12 | Tom | Sale | Forecast |15
AB587 |2019 | 11 | Tom | Stock | Actual |1455
This is a table with about 300,000 rows with all the SKUs and a couple of year's worth of transactions for all customers, and this gets into a very very useful pivot table that is used extensively. I now need to add something to the data to make the table even more useful.
I have the forecast for purchases and sales for the whole year along with the actuals of course and they follow the above pattern. I also have the stock for all the weeks but only the one in the past i.e. actuals only. I don't have the stock forecast, which is what I want to add. The calculation is as simple as:
Stock from previous week + Purchase forecast from this week - Sale forecast from this week
The end result which I am expecting is that there will now be more rows added which will have as an example:
AB587 |2019 | 12 | Tom | Stock | Forecast |1640
(I am using numbers from above to calculate)
This will now enable me not only to pivot Purchase and Sales but also stock levels which will be game changing.
I would love for anyone to help me with this in Power Query (I have tried a number of methods over weeks but have not cracked it)
To try and solve it myself:
I appended more rows essentially appending Week-1 data for all actual weeks from my source reducing potentially some calculation time. Then I pivoted my "Transaction column" leading to new columns i.e. Purchase, Sale, Stock and Stock-1, which made the Stock forecast calculation easy (that's what it appears to be).
The thing which I did not think about is: this is only good to calculate the first week stock forecast, but then there is no way that I know to use that just calculated stock forecast to calculate the next week's stock forecast.
Basically there is no way to save that stock forecast that I just calculated to be used for the next week's calculation.
I'm not clear on what you are asking when you say you say you want to use the "calculated stock forecast to calculate the next week's stock forecast". If you just want to generate the formula and result you gave as an example as a component of your dataset though, that is pretty simple.
Starting from this as a sample table of your data loaded into PQ that I'm calling "Data Table":
I create two reference queries based off it called StockForecast and CombinedDataTable
In the "StockForecast" query we will add three custom columns. Two are the CalcYear and CalcWeek columns that take "Stock Actual" records and increase the week by one. The third is a CalcValue column that takes "Sale Forecast" records and makes the value in those negative. The code in the editor looks like this:
Source = DataTable,
#"Added Custom" = Table.AddColumn(Source, "CalcYear", each
if [Transaction] = "Stock" and [Type] = "Actual" then
(if [Week] = 52 then [Year] + 1 else [Year])
else [Year]),
#"Added Custom1" = Table.AddColumn(#"Added Custom", "CalcWeek", each
if [Transaction] = "Stock" and [Type] = "Actual" then
(if [Week] = 52 then 1 else [Week] + 1)
else [Week]
),
#"Added Custom2" = Table.AddColumn(#"Added Custom1", "CalcValue", each
if [Transaction] = "Sale" and [Type] = "Forecast" then
[Value] * -1
else [Value]
),
Then you use the Group function and aggregate by Stock, Customer, CalcYear and CalcWeek, with a Sum on the CalcValue function. This gets the Stock Forecast value you are looking for. After that it's just a matter of adding a couple columns for identification and some cleanup.
#"Grouped Rows" = Table.Group(#"Added Custom2", {"Stock", "Customer", "CalcYear", "CalcWeek"}, {{"Value", each List.Sum([CalcValue]), type number}}),
#"Added Custom3" = Table.AddColumn(#"Grouped Rows", "Transaction", each "Stock"),
#"Added Custom4" = Table.AddColumn(#"Added Custom3", "Type", each "Forecast"),
#"Renamed Columns" = Table.RenameColumns(#"Added Custom4",{{"CalcYear", "Year"}, {"CalcWeek", "Week"}})
in
#"Renamed Columns"
Then end result of the data looks like this:
Then just go to the CombinedDataTable query, append the StockForecast query, and you have Stock Forecast values in your dataset.

Filter companies that have at least 3 specific products

I have an excel pivot table (and a table dataset behind) that has the structure like the one below. How can I filter/show only companies (Col A) with Products (Col B) 1 AND 2 AND 3? Sounds like something easy but can't find a way to do that. No problem by achieving this using Power Query (available in Power BI or Excel).
A1: Company 1 | B1: Product 1
A2: Company 1 | B2: Product 2
A3: Company 1 | B3: Product 3
A4: Company 1 | B4: Product 4
A5: Company 2 | B5: Product 1
A6: Company 3 | B6: Product 1
A7: Company 4 | B7: Product 1
A8: Company 4 | B8: Product 2
A9: Company 4 | B9: Product 3
A10: Company 4 | B9: Product 4
A11: Company 4 | B9: Product 5
Here's an approach using Power Query.
Starting with this brought into Power Query from the table in Excel:
I then group on Company (Transform > Group By):
Then I add a new custom column (Add Column > Custom Column) to flag whether each company has the 3 products included in its associated grouped table's Product column:
Then I filter out the FALSE entries from the new custom column (use button at top right of Custom column):
Then I expand the Products column from the embedded table in the AllData column (use button at top right of AllData column).
Then I remove the Custom column:
Here's the M code:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Company", type text}, {"Product", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Company"}, {{"AllData", each _, type table}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each List.ContainsAll([AllData][Product], {"Product 1","Product 2","Product 3"})),
#"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Custom] = true)),
#"Expanded AllData" = Table.ExpandTableColumn(#"Filtered Rows", "AllData", {"Product"}, {"Product"}),
#"Removed Columns" = Table.RemoveColumns(#"Expanded AllData",{"Custom"})
in
#"Removed Columns"
Basically, you'll need to do a couple of things to do this entirely in Excel:
Add a new table that lists the products, with a column indicating whether that product is included/flagged:
Update your company/product table to have 2 helper columns: One to VLOOKUP whether the product is flagged, and one to indicate whether a company has all 3 flagged products:
The first helper column would use a formula like =VLOOKUP([#Product],tProducts,2,FALSE).
The second helper column would use a formula like =COUNTIFS([Company],[#Company],[Product Flagged],TRUE)>=3.
Rows with a TRUE in Column D have 1 each of Products 1, 2, and 3 (unless you have rows with duplicate company/product combinations, where it gets a bit trickier):
In your pivot table, you can filter by this helper column:

Resources