Convert SQL function to PowerBI Measure

I’m looking to convert this SQL function into a PowerBI Dax measure. I need the dax measure to read SELECTEDVALUE of ‘tblInventoryHistory'[LocNo], ‘tblInventoryHistory'[ItemNo] and tbl’Date'[Date].

any help would be appreciated.

USE [Pos]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[DaysOnHand]
       (
       @LocNo int,
       @ItemNo int,
       @AsOf datetime
       )
RETURNS int
AS
       BEGIN
              Declare @hasinv int
              Set @hasinv = 
              (
                     select top 1 
                           Case When IsNull(OnHandAfter,0) <= 0 Then 0 Else 1 End as INV  
                     from 
                           tblInventoryHistory 
                     where 
                           LocNo = @LocNo
                     and
                           ItemNo = @ItemNo
                     and
                           AsOfDate <= @AsOf    
                     order by
                           AsOfDate Desc, AsOfTime Desc
              )
              RETURN IsNull(@hasinv, 0)
       END

I was able to add this invoked function when I leveraged parameters, but I need this to be a measure due to the dynamic and end-user controlled report.

It will be something very similar to the below – hopefully this will get you close to what you are needing.

YourMesure = 
  var curLoc = SELECTEDVALUE('tblInventoryHistory'[LocNo])
  var curItem = SELECTEDVALUE('tblInventoryHistory'[ItemNo])
  var curDate = LASTDATE('tblDate'[Date])

  var result = CALCULATE(
    COUNTROWS('tblInventoryHistory'),
    REMOVEFILTERS('tblDate'[Date]),
    'tblInventoryHistory'[LocNo] = curLoc &&
    'tblInventoryHistory'[ItemNo] = curItem &&
    'tblInventoryHistory'[AsOfDate] <= curDate
  )

  RETURN IF(result > 0, 1, 0)

If this is far-off then do update your question and share more on the Power BI data model.

Leave a Comment