简体   繁体   中英

Consecutive Absent/Worked Days Power BI Measure

I am current trying to Dynamically Calculate Consecutive worked and absent days for a group of employees, however this as proven to be quite a difficult task. The RAW table looks something like this:

Date ID Absent
6/1/2021 1234 1
6/2/2021 1234 1
6/32021 1234 1
6/4/2021 1234 0
6/1/2021 6789 1
6/2/2021 6789 0

I would like to use Dax (not Power Query) to calculate the consecutive days they were absent, the closest I have come to a solution is the following, Shout out SQLBI :

DaysWith0 = 
VAR CurrentDate = MAX('Calendar'[Date])
VAR FirstDateEver =  CALCULATE(MIN( 'Calendar'[Date]), REMOVEFILTERS())
VAR PrevWorked =
    CALCULATE(
        MAX('RawDataTable'[Date]),'Calendar'[Date] <= CurrentDate) 
VAR PrevDate = COALESCE(PrevWorked,FirstDateEver)
VAR Result = INT(CurrentDate - PrevDate)  
RETURN
    Result

But this only counts the consecutive days that have no data (no schedule). I need 2 measures that shows the consecutive worked days, and the consecutive absents.

This looks like a classic Gaps-and-Islands

Example

Select DateR1 = min(Date)
      ,DateR2 = max(Date)
      ,ID
      ,Absent = sum( case when Absent=1 then 1 else 0 end )
      ,Worked = sum( case when Absent=0 then 1 else 0 end )
 From  (
        Select *
              ,Grp = datediff(day,'1900-01-01',Date) - row_number() over (partition by ID,Absent order by Date) 
         From YourTable
       ) A
 Group By ID,Grp
 Order By ID,min(Date)

Results

DateR1      DateR2      ID      Absent  Worked
2021-06-01  2021-06-03  1234    3       0
2021-06-04  2021-06-04  1234    0       1
2021-06-01  2021-06-01  6789    1       0
2021-06-02  2021-06-02  6789    0       1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM