Calculate running total for a prior year - dax

The following code works properly, calculates the sum of CLIN Total for all of FY 2021. I am trying to calculate the sum up to today's date, i.e., if today is July 01,2022, I want to calculate the sum for FY 2021 through July 01, 2021.
Cum FY21 Invoice Total =
CALCULATE(
SUM('Invoice Amounts'[CLIN Total]),
FILTER(
ALL('Calendar'),
'Calendar'[Fiscal Year] = 2021
&& 'Calendar'[Date] < MAX('Calendar'[Date])
&& 'Calendar'[Date] < NOW())
)
I tried many variations of the following to replace the second filter, but can't find the right command. Dax doesn't seem to accept the now() in this context, but I'm not sure what the right one should be.
&&'Calendar'[Date]< DATEADD(now(),-1,YEAR)

This approach should help you to solve the issue.
VAR FirstDayThisYear =
SAMEPERIODLASTYEAR(STARTOFYEAR(Calendar'[Date])
VAR LastDayThisYear =
SAMEPERIODLASTYEAR(
LASTDATE(Calendar'[Date])
)
VAR SetOfDates=
DATESBETWEEN(
Calendar'[Date]
,FirstDayThisYear
,LastDayThisYear
)
RETURN
CALCULATE(
SUM('Invoice Amounts'[CLIN Total]),
,SetOfDates=
)

Related

Performance enhancement in DAX query

I have Power BI DAX query used in a measure. It takes longer time to execute. Can anyone please help me with this?
MEASURE FACT_CONSOL_BALANCE_OL[Measure 4] =
SWITCH (
TRUE (),
CONTAINS (
DIM_ANALYTIC_STRUCT_ACCOUNT,
DIM_ANALYTIC_STRUCT_ACCOUNT[STRUCTURE_NODE (groups)], "1 - CURRENT ASSETS"
), SUM ( FACT_CONSOL_BALANCE_OL[BALANCE] ),
CONTAINS (
DIM_ANALYTIC_STRUCT_ACCOUNT,
DIM_ANALYTIC_STRUCT_ACCOUNT[STRUCTURE_NODE (groups)], "2 - NON - CURRENT ASSETS"
), SUM ( FACT_CONSOL_BALANCE_OL[BALANCE] ),
SUM ( FACT_CONSOL_BALANCE_OL[BALANCE] ) * -1
)
Performance Result on DAX Studio:
Can you please try this code, see if It solves your problem. I tried to write it without contains() function.
MEASURE FACT_CONSOL_BALANCE_OL[Measure 4] =
SUMX (
FACT_CONSOL_BALANCE_OL,
VAR Balance =
SWITCH (
RELATED ( DIM_ANALYTIC_STRUCT_ACCOUNT[STRUCTURE_NODE (groups)] ),
"1 - CURRENT ASSETS", FACT_CONSOL_BALANCE_OL[BALANCE],
"2 - NON - CURRENT ASSETS", FACT_CONSOL_BALANCE_OL[BALANCE],
FACT_CONSOL_BALANCE_OL[BALANCE] * -1
)
RETURN
Balance
)

Comparison MTD to Previous month based on number of working days with DAX

I'm working with an IT department that wants to see their trend for submitted and closed tickets MTD vs Previous Month, but they want to account for the number of working days so far this month, and compare to the amount of tickets in the same number of working days the previous month. I have a date table with a column marking work days, and another to count the working day in each month.
This is what I had before to find the +/- compared to the previous month, but comparing the current date to the same day last month:
IF(
TOTALMTD(CALCULATE(COUNTA(' Ticket'[Name]),
'Ticket'[CreatedDateID]<>BLANK(), USERELATIONSHIP('Ticket'[CreatedDateID],'Date'[DateID]) ),
'Date'[Date])
>
CALCULATE(COUNTA('Ticket'[Name]),
AND('Date'[Date]>=DATE(YEAR(TODAY()), MONTH(TODAY())-1, 1), 'Date'[Date]<=DATE(YEAR(TODAY()), MONTH(TODAY())-1, DAY(TODAY()))),
USERELATIONSHIP('Ticket'[CreatedDateID],'Date'[DateID]) )
,
"+" & TOTALMTD(CALCULATE(COUNTA('Ticket'[Name]),
'Ticket'[CreatedDateID]<>BLANK(), USERELATIONSHIP(' Ticket'[CreatedDateID],'Date'[DateID]) ), 'Date'[Date])
-
CALCULATE(COUNTA(' Ticket'[Name]),
AND('Date'[Date]>=DATE(YEAR(TODAY()), MONTH(TODAY())-1, 1), 'Date'[Date]<=DATE(YEAR(TODAY()),MONTH(TODAY())-1,DAY(TODAY()))),
USERELATIONSHIP('Ticket'[CreatedDateID],'Date'[DateID]) )
,
TOTALMTD(CALCULATE(COUNTA('LoanForce Ticket'[Name]),
'LoanForce Ticket'[CreatedDateID]<>BLANK(), USERELATIONSHIP('LoanForce Ticket'[CreatedDateID],'Date'[DateID]) ), 'Date'[Date])
-
CALCULATE(COUNTA('LoanForce Ticket'[Name]),
AND('Date'[Date]>=DATE(YEAR(TODAY()), MONTH(TODAY())-1, 1), 'Date'[Date]<=DATE(YEAR(TODAY()),MONTH(TODAY())-1,DAY(TODAY()))),
USERELATIONSHIP('LoanForce Ticket'[CreatedDateID],'Date'[DateID]) )
)
Sample of Date Table
Can anyone assist in a measure that will take total tickets created this month and compare it to the tickets created previous month in the same amount of work days?
Where is the problem? As you say, you have "Working Days MTD" then we should use it.
Measure =
var __CurrentMonthWorkDaysPassed = calculate( MAX(Table[Working Days MTD]), FILTER(ALL(Table[Date]), Table[Date] >= DATE(year(TODAY()),MONTH(TODAY()),1) && Table[Date] <= TODAY()))
var __TicketInCurrentMonth = calculate(count(Table[ColumnToCount]), FILTER(ALL(Table), Table[Working Days MTD] <= __CurrentMonthWorkDaysPassed &&
Table[Date] >= DATE(year(TODAY()),MONTH(TODAY()),1) && Table[Date] <= TODAY() && Table[Is Working day] = 1 ))
var __TicketInPreviousMonth = calculate(count(Table[ColumnToCount]), FILTER(ALL(Table), Table[Working Days MTD] <= __CurrentMonthWorkDaysPassed &&
Table[Date] >= DATE(year(TODAY()),MONTH(TODAY()) -1 ,1) && Table[Date] < DATE(year(TODAY()),MONTH(TODAY()) ,1) && Table[Is Working day] = 1 ))
return
__TicketInCurrentMonth / __TicketInPreviousMonth

How to obtain first date of each month based on given year range in Nifi flow

I would like to know what could be the best way to obtain the starting date values for each month based on the date range.
For example: If I am given a year range of 2015-11-10 and 2018-01-15(format YYYY-mm-dd). Then I would like to extract following dates:
2015-12-01
2016-01-01
.
.
2018-01-01
You can try to use this flow for generating the first day of each month in the provided date range.
Overall flow
Step 1 Configuration: Start
Step 2 Configuration: Configure Date Range
Provide the start and end dates as configuration parameters via this step.
Step 3 Configuration: Generate First Dates For Months
This uses a Groovy script, which is provided below
Groovy script
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'yyyy-MM-dd';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("start_date"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("end_date"));
allFirstDates = "";
Calendar calendar = Calendar.getInstance();
Set firstDaysOfMonths = new LinkedHashSet();
for (int i = 0; i <= endDate-startDate; i++) {
calendar.setTime(startDate.plus(i));
calendar.set(Calendar.DAY_OF_MONTH, 1);
firstDayOfMonth = calendar.getTime();
if (firstDayOfMonth.compareTo(startDate) >= 0) {
firstDaysOfMonths.add(calendar.getTime().format(DATE_FORMAT));
}
}
firstDaysOfMonths.each {
firstDayOfMonth -> allFirstDates = allFirstDates + firstDayOfMonth + "\n";
}
flowFile = session.putAttribute(flowFile,"all_first_dates", allFirstDates );
session.transfer(flowFile,REL_SUCCESS)
Step 4 Configuration: View Result
Output of run:
When the flow is run, the attribute all_first_dates will be populated with the first dates of each month in the date range.

Including for loop in subsets

I want to calculate the weekly averages of the the load for two ships with containers. One ship sails at Sunday and the other on Wednesday. I have a big excel file with bookings.I will load up a small part of this file in the following link: https://docs.google.com/spreadsheets/d/1BxHTClTkrQzIzZzG5vXXnvKtV0_az83PGJ2ghBaAQr0/edit?usp=sharing
The first ship gets the containers that should be delivered on Monday (Mo), Tuesday(Di) and Wednesday (Mi). The second ship should deliver the containers demanded in the other port for Thursday (Do), Friday (Fr), Saturday(Sa) and Sunday(So). The data contains information about the containers from 2017-01-01 till 2018-07-31. These are 82 full weeks. I would like to make a vector with length 82, with each number the amount of containers of the days combined for that week. For example, the first number of the vector should be the demand of containers for Monday, Tuesday and Wednesday in the first week. So, I want to create a vector, one per ship, that contains information about the amount of containers that should be loaded on this ship. A vector of 82 weeks, to see which weeks we had low demand and the mean etc.
Can anyone please help me?
Here is the beginning of my code:
containers <- "https://docs.google.com/spreadsheets/d/1BxHTClTkrQzIzZzG5vXXnvKtV0_az83PGJ2ghBaAQr0/edit?usp=sharing"
#Containers between Rotterdam and Duisburg
containersRTMDUI <- subset(containers, containers$Laadhaven == "Rotterdam" & containers$Loshaven == "Duisburg")
#I used to do this in subsets, because I could not make a loop
Week1 <- subset(containersRTMDUI, containersRTMDUI$Datum1 >= "2017-01-02" &
containersRTMDUI$Datum1 < "2017-01-09" & containersRTMDUI$Dag1 = "Mo" &
containersRTMDUI$Dag1 = "Di" &containersRTMDUI$Dag1 = "Mi")
Week2 <- subset(etc..)
Of course, the hard point comes by the fact that for some days there is no demand.
I think I got it. One approach with data.table:
# read in data as a data.table
library(data.table)
dt <- data.table(read.csv("path/to/file", stringsAsFactors = F))
# rename variables to english (
# there are shorter ways to do this, but I like to keep track)
setnames(dt, old = "ISO", new = "containter_type")
setnames(dt, old = "F.E", new = "full_empty")
setnames(dt, old = "Gewicht", new = "weight")
setnames(dt, old = "Laadhaven", new = "pickup_port")
setnames(dt, old = "Laadterminal", new = "pickup_terminal")
setnames(dt, old = "Loshaven", new = "dropoff_port")
setnames(dt, old = "Losterminal", new = "dropoff_terminal")
setnames(dt, old = "Datum1", new = "pickup_date")
setnames(dt, old = "Dag1", new = "pickup_dow")
setnames(dt, old = "Datum2", new = "dropoff_date")
setnames(dt, old = "Dag2", new = "dropoff_dow")
# convert date variable to date-type (instead of factor/string)
dt[ , pickup_date := as.Date(pickup_date, "%d.%m.%Y")]
dt[ , dropoff_date := as.Date(dropoff_date, "%d.%m.%Y")]
# create a week variable
dt[ , week := lubridate::week(pickup_date)]
# create a variable (MTW) by day-of-week
# MTW=1 for mon, tues, wed; MTW=0 for thurs, fri, sat, sun
dt[ , MTW := pickup_dow %in% c("Mo", "Di", "Mi")]
# count the number of rows by week and MTW
result <- dt[ , .(nrows = .N), by=.(week, MTW)]
# print result
result
# fill in 0 weeks
dt2 <- data.table(week = rep(1:7, each=2), MTW = rep(c(T,F), each=7))
result <- merge(result, dt2, by=c("week", "MTW"), all=T)
result[is.na(nrows), nrows := 0]
# print updated result
result

Calculate year week number from given period in VBScript

Scenario: Trying to find out the End Week Number(current year's week number) and Start Week Number using a given period. Suppose PeriodWeeks = 10. That means from today's week number to last 10 weeks which surely will go to last year in current situation.
Code I have:
perdiodWeeks = 10 ' this is a constant in the code
periodMonths= periodQtrs * 3 ' this calculates month from given number of quarters
endDate = DateAdd("m",-1,Date)
endYear = DatePart("yyyy", endDate)
endMonth = DatePart("m", endDate)
startDate = DateAdd("m", -(periodMonths-1), endDate)
startYear = DatePart("yyyy", startDate)
startMonth = DatePart("m", startDate)
How can I calculate the following?
startYW ' start year week number
endYW ' end year week number
where value would be endYW = 201506 and startYW = perdiodWeeks from endYW. 06 is the current Week Number of 2015
Calculate the initial date (substract #weeks*7) and use the available functions to retrieve the required information
Option Explicit
Dim periodWeeks
periodWeeks = 10
Dim dateToday, dateStart
dateToday = Now()
dateStart = DateAdd("d",periodWeeks*-7, dateToday)
Dim weekToday, weekStart
weekToday = DatePart("ww",dateToday)
weekStart = DatePart("ww",dateStart)

Resources