MS Access - Multiple Queries shared Criteria in time stamp date range - date-range

MS Access 2016,
I have Multiple queries - approximately 120 - that are gathering temp history based on date criteria that I currently update manually for each query - >=#8/1/2021# And <#9/1/2021# - for the month of August 2021.
What would be the best solution to update this in one place so all queries could refer to that one date range?
Sample Query: (Usually 43 parameter points)
SELECT
History1HourAverage.TimeStamp,
History1HourAverage.Parameter001,
History1HourAverage.Value001,
History1HourAverage.Parameter002,
History1HourAverage.Value002,
History1HourAverage.Parameter003,
History1HourAverage.Value003,
History1HourAverage.Parameter004,
History1HourAverage.Value004
FROM History1HourAverage
WHERE
(
(
***(History1HourAverage.TimeStamp)>=#8/1/2021#
AND (History1HourAverage.TimeStamp)<#9/1/2021#
)***
AND ((History1HourAverage.Parameter001)="10S8MApp.nvoSpaceTemp")
AND ((History1HourAverage.Parameter002)="10S9MApp.nvoSpaceTemp")
AND ((History1HourAverage.Parameter003)="10S10MApp.nvoSpaceTemp")
AND ((History1HourAverage.Parameter004)="10S11MApp.nvoSpaceTemp")
);
Thank you

A couple of options:
Either
Add a table called DateRange with two fields, StartDate and EndDate. Enter one record in that table with the date range that you want to use for your queries. Edit each of your queries and include the DateRange table. Set the criteria for the query to WHERE History1HourAverage.TimeStamp >= DateRange.StartDate And History1HourAverage.TimeStamp < DateRange.EndDate
Alternatively
Create a VBA module with two functions
Public Function StartDate() As Date
StartDate = #8/1/2021#
End Function
Public Function EndDate() As Date
EndDate = #9/1/2021#
End Function
Set your query criteria for the query to WHERE History1HourAverage.TimeStamp >= StartDate() And History1HourAverage.TimeStamp < EndDate()
When you want to use a different date range you either (1) edit the data in DateRange table, or (2) edit your functions to return the new dates.

Related

How can I split weekly data to monthly using Excel/ Power Pivot?

My Data is in weekly buckets. I want to split the number into a monthly number but, since there is an overlap in days falling in both the months, I want a weighted average of the data in terms of days that fall in each of the months. For example:
Now, in the above picture, I want to split that 200 (5/7*200 in Jan, 2/7 in Feb). How can I do that using Excel/ Power Pivot/ Dax Functions? Any help here is much appreciated.
Thank you!
Assuming your fact table looks something like below. Values are associated with the starting date of the week it occurred.
Although it may actually be a more granular data, having multiple rows for each week with additional attributes (such as identifiers of a person, a store, depending on the business), what being shown below will work the same.
What we need to do first is to create a date table. We can do that in "Design" tab, by clicking "Date Table", then "New".
In this date table, we need to add a column for starting date of the week which the date of each row is in. Set the cursor to "Add Column" area, and input following formula. Then rename this column to "Week Start Date".
= [Date] - [Day Of Week Number] + 1
Now, we can define the measure to calculate the number allocated to each month with following formula. What this measure is doing is:
Iterating over each row of the fact table
Count the number of days for the week visible in the filter context
Add the value portion for the visible days
Value Allocation := SUMX (
MyData,
VAR WeekStartDate = MyData[Week]
VAR NumDaysInSelection = COUNTROWS (
FILTER (
'Calendar',
'Calendar'[Week Start Date] = WeekStartDate
)
)
VAR AllocationRate = DIVIDE ( NumDaysInSelection, 7 )
RETURN AllocationRate * MyData[Value]
)
Result in the pivot table will be looking like this.

Excel Power Pivot aggrating data through a many to 1 then 1 to many relationsips

I have 2 large tables in power pivot and I am trying to reconcile stockpile build grades to crushed stockpile grades. Please see example. I can create pivot table that contains the crushed grades but I am unable to find the right way to bring the stockpile grades though for the reconciliation high lighted in green in the attached example.
Thanks for any help or direction on where to look
In Power Query, create your lookup tables.
1) unique crushers, ID
2) Dates, ID
Here is a function to create a dates table, if you need one. After you invoke the function to get the column of dates, add another column for the ID.
/*--------------------------------------------------------------------------------------------------------------------
PQ Create a Dates Table, returning a single column of dates.
Inputs:
Start Date | Enter the year as yyyy, month as mm, day as dd
End Date | Enter the year as yyyy, month as mm, day as dd
Increments | One row will be returned per increment.
Author: Jenn Ratten
Edits:
07/16/18 | Modified query copied from the internet.
10/01/19 | Converted to a function.
--------------------------------------------------------------------------------------------------------------------*/
let
fDatesTable = (StartYear as number, StartMonth as number, StartDay as number, EndYear as number, EndMonth as number, EndDay as number, IncrementDays as number, IncrementHours as number, IncrementMin as number, IncrementSec as number) as table =>
let
StartDate = #date(StartYear,StartMonth,StartDay),
EndDate = #date(EndYear,EndMonth,EndDay),
Increments = #duration(IncrementDays,IncrementHours,IncrementMin,IncrementSec),
DatesTable = Table.FromColumns({List.Dates(StartDate, Number.From(EndDate) - Number.From(StartDate), Increments)}, type table[Date]),
ChangeType = Table.TransformColumnTypes(DatesTable,{{"Date", type date}})
in
ChangeType
in
fDatesTable
Load all of the tables to the data model.
Go to Power Pivot, diagram view, and create your relationships.
Lookup Crusher to data tables 1 and 2
Lookup Date to data tables 1 and 2
Go to Data View on data tables 1 and 2, add 2 new columns for the lookup IDs. You can specify the column header and the formula at one time by clicking in first cell and using this syntax, then either press enter or click the check mark in the formula bar.
Dates Lookup ID:=RELATED(lookup_dates[ID])
Crusher Lookup ID:=RELATED(lookup_crusher[ID])
Optional, but a good practice....
Right-click the new fields you just created and select "hide from client tools". Also hide the date and crusher fields on both data tables, and the ID field on both lookup tables. When you are creating pivots to summarize data from more than one table, the text fields that you place on your pivot table should be the fields that are shared (aka the lookup tables). This helps to minimize pivots in which the grand totals don't match the sum that you actually see on the table. If you hide the fields, it reminds you of that. There are exceptions of course, but this is a good rule of thumb.
Now create measures to sum the tons and any other math calculations you'd like. With the measures, start simple and let the pivot do the slicing. Put the measures in the values section of the pivot table.
Sum of Source Tons:=sum(Table1[Tons])
Sum of Destination Tons:=sum(Table2[Tons])

DAX Excluding Assets Out of Contract Date

I am trying to create a measure that will sum invoices totals for all assets but exclude assets whose contracts have expired. The tables look something like this:
Service Data:
Invoice Amount
Asset Key
Invoice Date
Asset Data:
Asset Key
Contract Start Date
Contract End Date
I am also using a date table that is attached to a slicer on the main page of my dashboard. I would like to be able to select a date range on the slicer and have it limit which assets' invoices in includes in the total in respect to the date range selected on the slicer.
Here is what I was attempting so far:
NewISA =
var enddate = MIN(F_Service_Invoice_Summary[Invoice_Date])
Return
IF(
enddate <= F_Asset[End_Date],
SUM(F_Service_Invoice_Summary[Invoice_Segment_Amount]),
0)
Assuming you have a relationship between the ServiceData and AssetData on the AssetKey field and that you have a relationship between your DateTable and ServiceData table on the InvoiceDate field, the following formula should work:
Total Invoiced Active Contracts =
CALCULATE (
SUM ( ServiceData[Invoice Amount] ),
FILTER (
AssetData,
AssetData[Contract Start Date] <= MIN ( DateTable[Date] )
&& AssetData[Contract EndDate] > MAX ( DateTable[Date] )
)
)
We can use MIN(datetable[date]) and MAX(datetable[date]) to determine the interval that is filtered in the datetable to only select contracts that are active during the whole period. Please keep in mind that if you do not select an interval, the formula will only return contracts that started before the first date in your datetable and end after the last date in your datetable.

Power Query - The field 'xxx' of the record wasn't found

I want to add a new column to a source of data.
The new column's value is based on the data of the current row (To Resolved date and From Activated date) as well as data from another query (Calendar). Here is the a screenshot of the source data I am working on:
I am trying to get the number of rows of the other source (Calendar) that are within the range [From Activated date, To Resolved date]. For now, I have this formula for the new column (without the counting yet):
= Table.SelectRows(Calendar, each _[Date] >= [From activated date] and _[Date] <= [To Resolved date])
However, it does not work because Power Query does not find the columns From Activated date and To Resolved date in the Calendar query.
Expression.Error: The field 'From activated date' of the record wasn't
found.
Details:
Date=2017-01-01
Year=2017
MonthNumber=1
MonthName=January
Day=1
Weekday=1
WorkingDays=0
Question
How can I get the current values of From Activated date and To Resolved date for the current row ?
Add another query as a function - in this case, I named it 'CalendarRows':
(StartDate, EndDate) =>
let
Source = Table.RowCount(Table.SelectRows(Calendar, each [Date] >= StartDate and [Date] <= EndDate))
in
Source
Now add a column to your data table, referencing this function:
= Table.AddColumn(#"Previous Step", "Calendar Rows", each CalendarRows([From activated date], [To Resolved date]))

Get last item with date range and name filter in google sheets

I have the below set of records in Google Sheets. I would like to filter the rows with specific name and date range. Once I have the filtered data, I would like to fetch the last row's final amount cell data.
Ex: I would like to fetch final amount as 300 if my date(dd/mm/yyyy) range is 01/01/206 to 11/06/2016 and Name selection is 'Sandeep'.
As I have experience SQLite db, I have inserted the same records in DB and got the expected result using the below query.
select Final from MyTable where Date in (select max(Date) from MyTable WHERE Date BETWEEN '01/01/2016' AND '11/06/2016' and name = "Sandeep")
But I am not getting idea how to use multiple select statements in google sheets. It is ok for me to get result using any other way. So please help me to get the result as explained above.
= QUERY (A1:E50,"Select F where A > date '2016-1-1' and A < date '2016-6-11' and B ='Sandeep' order by A desc limit 1")
Use Column IDs A,B,C instead of name, income. Multiple columns can be given in a single Select clause separated by a ,
Dates in where clause should be written in yyyy-mm-dd format only(regardless of the format of dates in actual column)
See if this works
=index(E:E, max(filter(row(A:A), A:A>date(2016, 1, 1), A:A<date(2016, 6, 11), B:B="Sandeep")))
If you want to include start and end date, change > to >= and < to <=.

Resources