Trailing three years filter

The objective of this example is to retrieve dates from three years prior to the current year through the current date. For example, on October 18th, 2017, the query should retrieve January 1st, 2014 through October 18th, 2017. This requirement ensures that three full years of historical data, plus the current year, is always available to support reporting.

The starting date and current date values for the filter condition are computed via Date and DateTime M functions and assigned variables names (StartDate, CurrentDate). Since the starting date will always be on January 1st, it's only necessary to compute the starting year and pass this value to the #date constructor. Finally, the two date variables are passed to the Table.SelectRows() function to implement the filter on the Reseller Sales fact table view: 

let
//Trailing Three Year Date Values
CurrentDate = DateTime.Date(DateTime.LocalNow()),
StartYear = Date.Year(CurrentDate)-3,
StartDate = #date(StartYear,1,1),
//Reseller Sales View
Source = AdWorksSQLServer,
ResellerSales = Source{[Schema = "BI", Item = "vFact_ResellerSales"]}[Data],
//Trailing Three Year Filter
FilterResellerSales =
Table.SelectRows(ResellerSales, each [Order Date] >= StartDate and [Order Date] <= CurrentDate)
in
FilterResellerSales

As shown in the View Native Query dialog available in the Applied Steps window of the Power Query Editor, the custom filter condition is translated into a T-SQL statement for the source SQL Server database to execute:

Query Folding of three year filter condition 

Note that the order of the variables in the expression doesn't impact the final query. For example, the two Reseller Sales view variables could be specified prior to the three date variables and the final FilterResellerSales variable would still generate the same SQL query. Additionally, be advised that M is a case-sensitive language. For example, referencing the variable defined as StartDate via the name Startdate will result in a failure.

Single-line comments can be entered in M queries following the double forward slash (//) characters per the trailing three years example. Multiline or delimited comments start with the (/*) characters and end with the (*/) characters, just like T-SQL queries for SQL Server.

If the requirement was only to retrieve the trailing three years of data relative to the current date (for example, October 18th, 2014 through October 18th, 2017) the StartDate variable could be computed via the Date.AddYears() function, as follows:

//Trailing three years (e.g. October 18th, 2014 through October 18, 2017)
CurrentDate = DateTime.Date(DateTime.LocalNow()),
StartDate = Date.AddYears(CurrentDate,-3)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.182.62