Forum Discussion
amikm
4 years agoHelper V
SQL to DAX conversion
I am trying to get the equivalent logic in DAX for below SQL declare @date datetime declare @warehouse nvarchar(225) declare @province nvarchar(225) set @Transdate = '2021-09-18 00:00:00.000'...
- 4 years ago
Happy New Year, pal! Thanks for tagging me for some tricky game of DAX.
I'm afraid you were mislead by PO's sql; first of all, I simplied it this way,
declare @Transdate datetime declare @warehouse nvarchar(225) declare @province nvarchar(225) set @Transdate = '2016-07-11 00:00:00.000' set @province = 'BC' set @warehouse = 'BC-52' ; with main1 as ( SELECT * , ROW_NUMBER() OVER(Partition by itemid ORDER BY transdate DESC) AS [rn] , SUM([Amount]) OVER (PARTITION BY ItemID) AS [Total] FROM [dbo].[MATDW SAMPLE DATA] dt WHERE transdate <= @Transdate and province = @province and warehouseid = @warehouse) select * from main1 where [rn]=1DAX
Total = VAR __cat = MAX( 'MATDW SAMPLE DATA'[Category] ) VAR __summary = CALCULATETABLE( ADDCOLUMNS( ADDCOLUMNS( SUMMARIZE( 'MATDW SAMPLE DATA', 'MATDW SAMPLE DATA'[ITEMID], 'MATDW SAMPLE DATA'[WarehouseID] ), "@amt", CALCULATE( SUM( 'MATDW SAMPLE DATA'[Amount] ) ), "@maxdate", CALCULATE( MAX( 'MATDW SAMPLE DATA'[TRANSDATE] ) ) ), "@Cat", VAR __dt = [@maxdate] RETURN CALCULATE( MAX( 'MATDW SAMPLE DATA'[Category] ), 'MATDW SAMPLE DATA'[TRANSDATE] = __dt ) ), ALLSELECTED( 'MATDW SAMPLE DATA'[Category] ) ) RETURN IF( __cat IN SELECTCOLUMNS( __summary, "_cat", [@Cat] ), SUMX( FILTER( __summary, [@Cat] = __cat ), [@amt] ) )
rbriga
4 years agoImpactful Individual
Is it possible for you to save this as a stored procedure on the SQL Server (or view, but you'll need to do away with the declared variables),
Then call it in Power Query?
Not only would it save you the trouble of re-creating your hard work, it would also move that transformation to to source, which is preferable.