Forum Discussion
Convert SQL into DAX
- Anonymous3 years ago
Hi amikm ,
To convert the SQL code to DAX, you can try the following approach:
Replace the FROM and JOIN clauses with a FILTER function that filters the rows in the relevant tables based on the conditions in the WHERE clause.
Replace the SELECT and COUNT clauses with a CALCULATE function that counts the distinct AccountNumber values using the DISTINCTCOUNT function.
Here's the resulting DAX measure:
Count of Distinct Account Numbers =
CALCULATE(
DISTINCTCOUNT(dimAccount[AccountNumber]),
FILTER(
factTable,
factTable[DateSk] = dimDate[DateSk]
&& dimDate[IsLastDayOfMonth] = 1
&& dimDate[DateKey] > "2020-11-30"
&& dimDate[DateKey] <= "2021-11-30"
&& ISBLANK(factTable[Sale])
&& factTable[IsDeleted] = FALSE
&& dimAccount[IsDeleted] = FALSE
),
FILTER(
dimAccount,
dimAccount[AccountKey] = factTable[AccountKey]
&& dimAccount[DateSk] = factTable[DateSk]
)
)
This measure should give you the same result as the SQL query.
Note: I replaced ISNULL(F.Sale ,0) = 0 with ISBLANK(factTable[Sale]) since DAX doesn't have an ISNULL function. In DAX, you can use the ISBLANK function to check if a value is NULL or an empty string.
I hope this helps! Let me know if you have any questions or if you need further assistance.
Best Regards,
Stephen Tao
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
Do I understand it correctly, that you would like to have Distinct count of Account numbers, where there was no sale at the end of each month?
To give you any advice, it would be good if you would provide some more detailed information like: are the sales data in your fact table per day (so you need to summ them up to the last day of month)? What would be the filtering context in your report - data displayed per month?
In principle, it is always better to have a calculation done as early as possible... so if you can calculate it via SQL directly on e.g. SQL server level, it is better (from performance point of view) then having it calculated by DAX.
I think it would not be easy to give you a single reply... especially if I think that also the SQL does not make too much sense (e.g. Why you need to put the last WHERE condition (A.AccountNumber NOT IN( ...) ?...isn't ISNULL(F.Sale ,0) = 0 condition sufficient?)