Daxquest
Daxquest
Text Functions :- Concatenate , ConcatenateX, Exact , Find , Mid, Trim ,Replace, Substitute , Search , Lower, Upper.
Stastical Functions :- Avg , AvgX , Count , CountX, MAX, MAXA, Min, RANKX
Time Intelligence Fun :- Total QTD, MTD, YTD, End Of Month , End Of Quarter , Last Date , Next Day/Month/Year
Date & Time Functions :- Date , DateDiff, Day, Edate, EoMonth, Hour, Minute , Weekday , Calendar
Filter Functions :- ALL, ALLEXCEPT, CALCULATE, LookupValue
Math & Trig Functions :- ABS , Even , Int , Round , Sum , SUMX
Logical Functions :- And , Coalesce , If , If error , Not , OR , Switch , True
TableManipulation Functions :- ADDCOLUMN, CROSSJOIN , Distinct , EXCEPT , Group BY , Union , Summarize.
Q: What are the DATE and TIME FUNCTIONS you have used ?
1. DATE It takes three arguments and returns the specified date in datetime format.
Syntax :- DATE(<year>, <month>, <day>)
Example :-
4. EDATE Returns the date that is the indicated number of months before or after the start date.
Syntax :- EDATE(<start_date>, <months>)
Example :- MATURITY_DATE = EDATE(Today(), 15)
Used to calculate maturity dates or due dates that fall on the same day of the month as the date of issue.
5. EOMONTH Returns the last day of the month in date time format.
Syntax :- EOMONTH(<start_date>, <months>)
here in month we can give 0-same month, 1- Next Month , -1 Prev month
Example :- EndOfMonth = EOMONTH(EMP(JOIN_DATE),1)
6. DAY It returns the Day from the date . return will be like 1,2 ….31
7. Month It returns the Month from the Date. In number format like (10,11,12 etc)
8. Year It returns the Year from the Date like 2020,2017 etc.
9. YEARFRAC It returns fraction of the year between two dates.
Syntax :- YEARFRAC(<start_date>, <end_date>, <basis>)
Example :- YEARFRAC("Jan 1 2007","Mar 1 2007") Here basis is optional. It
will return zero.(2007-2007).In basis use 2 to divide actual by 360.
10. Quarter It returns the quarter based on date. like 1, 2 ,3 4.
11. Hour/Minute/second It will return the hour/minute/second from the date given.
12. UTCTODAY() UTCTODAY returns the time value 12:00:00 PM for all dates. Today() also returns same.
13. UTCNOW() UTCNOW function is similar but returns the exact time and date.
14. NOW () it returns the current date and time that value updated each time you open the worksheet. The result of
the NOW function changes only when the column that contains the formula is refreshed. It is not updated
continuously. The TODAY function returns the same date but is not precise with regard to time; the time returned is
always 12:00:00 AM and only the date is updated.
15. WeekDay Returns a number from 1 to 7 identifying the day of the week of a date. By default the day ranges from
1 (Sunday) to 7 (Saturday).
Return type: 1, for week begins on Sunday (1) and ends on Saturday (7) Return type: 2, for Monday to
Sunday Return type: 3, week begins on Monday (0) and ends on Sunday (6).
16. WeekNum It Returns the week number for the given date and year according to the return_type value
The week number indicates where the week falls numerically within a year.
Syntax :- WEEKNUM(<date>, <return_type>)
A number that determines the Return value: use 1 when the week begins on Sunday; use 2 when
the week begins on Monday. The default is 1.
17. TIME Converts hours, minutes, and seconds given as numbers to a time in datetime format.
18. CALENDAR Returns a table with a single column named "Date" that contains dates from the specified start date
to end date, inclusive of those two dates. An error is occurred if start_date is greater than end_date.
Syntax :- CALENDAR(<start_date>, <end_date>).
19. CALENDARAUTO() Returns a table with a single column named "Date" that contains a contiguous set of dates.
The range of dates is calculated automatically based on data in the model.
Syntax : CALENDARAUTO([fiscal_year_end_month])
The date range returned is dates between the beginning of the fiscal year associated with MinDate and the end of
the fiscal year associated with MaxDate. In this example, the MinDate and MaxDate in the data model are July 1,
2010 and June 30, 2011.
CALENDARAUTO() will return all dates between January 1, 2010 and December 31, 2011.
CALENDARAUTO(3) will return all dates between March 1, 2010 and February 28, 2012
20. DATEADD() It will Returns either a table that contains a column of dates or a column in existing table, shifted
either forward or backward in time by the specified number of intervals from the dates in the current context.
Syntax :- DATEADD(<dates>,<number_of_intervals>,<interval>)
Here no_of_intervals will be 1,2,3 for forward or -1,2- for backward and interval can be year , month ,
quarter, day.
Example :- Column = DATEADD(Sheet1[Master Date],5,MONTH).
21. PARALLELPERIOD() :- The PARALLELPERIOD function is similar to the DATEADD function except that
PARALLELPERIOD always returns full periods at the given granularity level instead of the partial periods that
DATEADD returns. For example, if you have a selection of dates that starts at June 10 and finishes at June 21 of the
same year, and you want to shift that selection forward by one month then the PARALLELPERIOD function will
return all dates from the next month (July 1 to July 31); however, if DATEADD is used instead, then the result will
include only dates from July 10 to July 21.
22. DATESBETWEEN() It will returns a table or work as a filter to calculate functions that contains a column
of dates that begins with a specified start date and continues until a specified end date.
Syntax :- DATESBETWEEN (<dates>, <start_date>, <end_date>)
Example :- Sales between 1 may 2017 to 15 may 2017
SALES_1-15_May = Calculate([total_sales], datesbetween(Data[salesdate],’’01/05/2017”,”15/05/2017’))
Last_7_days_sale = Calculate([total_sales], datesbetween(Data[salesdate],today()-7,today()))
23. DATESINPERIOD() It will returns table or work as a filter to calculate functions that contains a column of
dates that begins with a specified start date and continues for the specified number and type of date
intervals.
Syntax :- DATESINPERIOD(<dates>, <start_date>, <number_of_intervals>, <interval>)
Example :- Calculate([total_sales],datesinperiod (data[salesdate],lastdate(data[salesdate]),-7,day))
It will return the total sales from the last seven date.
24. SAMEPERIODLASTYEAR() Returns a table that contains a column of dates shifted one year back in time from
the dates in the specified dates column. It is just equivalent to DATEADD(dates, -1, year)
Syntax :- SAMEPERIODLASTYEAR(<dates>)
Ex :- CALCULATE(SUM(Reseller[SalesAmount_USD]),SAMEPERIODLASTYEAR(DateTime[DateKey]))
Ans :- Both the functions work for fetching the data from other table.
Scenario: - In the context, let us consider a one-to-many relationship. If you have CUSTOMER master and FACT tables then
trying to create a relationship, then that would create a one-to-many relationship.
It means we have unique records on the customer table but multiple same values on the FACT table with reference to the
connected columns.
If you want to create a new calculated column on the CUSTOMER table then you need to use RELATEDTABLE DAX function.
On the other hand, when you want to create a calculated column on the FACT table then you need to use the RELATED
function.
Q. RELATED vs LOOKUPVALUE – which one to use?
Ans :- Both can be used to assign values from other.
RELATED:-
It is simple - only use one parameter.
It can work through multiple tables, if they are connected by the M-1 relation.
LOOKUPVALUE :- Retrieves a value based from a table based on FK from another table.
Tables don´t need any relation - so it can be used when the relation can´t be created.
LOOKUPVALUE can use multiple keys at the same time. So, for example, you can use not only a surname, but first name
and surname together.
LOOKUPVALUE doesn´t need the other table - it can take values from the table where LOOKUPVALUE formula takes place.
Typically, it takes values from other rows, using some key.
DEPTNAME = LookUPValue (Dept[deptName] , Dept(deptno) , emp(Dept)) Here DeptName is retrieval column and others
two are matching column.
Q. What is Calculated Column in Power Bi and why would you use them?
Ans:- Calculated Columns are DAX expressions that are computed during the models refresh process for each row of the
given column and can be used like any other column in the model.
Calculated columns are not compressed and thus consume more memory and result in reduced query performance.
Q. What is Calculated & Calculated table in DAX and diffrence between them ?
Ans :- The basic diffrence is calculate will return number and calculated table will return a Table.
Since a Measure return only one value (scalar value) , so calculate table cant be directly used for measure purpose
whereas Calculate can be used. If calculate table needs to be used in measure then it can be with conjuction of SUMX
which needs one table and expressions.
Q34. How would you create trailing X month metrics via DAX against a non-standard calendar?
Ans :- Use Calculate function to control filter context of measures.
ALL to remove exiting filter in Date dimension
Filter to identify which rows of the date dimension to use.
Ans :- Complex calculation requirements often involve writing compound or complex expressions. Compound expressions
can involve the use of many nested functions, and possibly the reuse of expression logic.
Using variables in your DAX formulas helps you write complex and efficient calculations.
Variables can: Improve performance Improve readability Simplify debugging Reduce complexity
EX :- Sales YoY Growth % =
VAR SalesPriorYear =
CALCULATE([Sales], PARALLELPERIOD('Date'[Date], -12, MONTH))
RETURN
DIVIDE(([Sales] - SalesPriorYear), SalesPriorYear)
Ans :- Summarize and GroupBy will help us to summarize the data based on the set of columns. For exaple we have a EMP
table and we need to summarize the data based on the department wise, we can apply the summarize.
Both are same but in Groupby we need to use currentgroup function to calculate any expression whereas in summarize we
don’t required any such things.
EX :- SAL_BY_DEPT = GroupBy (EmpTable , Emp(DEPT), “TOTALSAL”, SUMX(CurrentGroup(), EMp(SAL)));
Ans :- Sum is Aggregate function whereas SumX is Iterator function. Sum Calculates whole column in a table and SUMX
calculates sum row by row. Sum takes a column and it calculates vertically while SUMX takes a column and it calculates
horizontally, row by row.
Note :-whenever we have to do group-by something ,we can’t use measure so we have to use call col
Ans :- Count will count only number and date and no blank values, COUNTA will count anything text, date, number and no
blank values.
In CountX = Here we can count Product subcategory CAPS in list_price column or no of seller whose sales>100 soemthing
like that.
COUNTX(FILTER(Product,RELATED(ProductSubcategory[EnglishProductSubcategoryName])="Caps"), Product[ListPrice])
COUNTX function counts only values, dates. If the function finds no rows to count, it returns a blank where as COUNTAX do
for all.(strings as well).
Countrows – This function is used to count no of rows in a table. Only can be used with table
COUNTROWS(RELATEDTABLE(Reseller Sales)). It can also be used with filter and count something like country = ‘EMEA’
or sales > 500.
Ans :-
Note :- Here Values() function will return distinct unique values in a column.
Q.10.1 How to get sales between some range ?
Ans :- The same can be used with the help of AND Function.
ANS :- With the help of Format Function We can get the weekday , week name or month name . Actually it Converts a
value to text according to the specified format.
Syntax :- FORMAT(<value>, <format_string>)
Example :- 1. Week num = Format(Sales[date],1) here 1 is for Sunday or 2 for Monday.
2. Weekday = Format(Sales[date],”DDDD”) it shows the Full day name.
Similarly in <format_string> we can use “MMMM” for month name or currency etc.
Ans :-
Here Or function is used in weekends because they want it to calculate on either on Sunday or in Monday.
Ans :- Complex calculation requirements often involve writing compound or complex expressions. Compound
expressions can involve the use of many nested functions, and possibly the reuse of expression logic.
By Declaring a variable , we can reuse the value many times inside a DAX query. By So query will look more cleaner, easy to
read and understand its functions.
Using variables in your DAX formulas helps you write complex and efficient calculations.
Variables can: Improve performance Improve readability Simplify debugging Reduce complexity
EX :- Sales YoY Growth % =
VAR SalesPriorYear =
CALCULATE([Sales], PARALLELPERIOD('Date'[Date], -12, MONTH))
RETURN
DIVIDE(([Sales] - SalesPriorYear), SalesPriorYear)
Ans :- It will give the total year to year wise sales. Just for Jan to Dec 2017 it will give running total and again in 2018 jan to
dec it will give running total.
Q15. Diffrence between DISTINCT() and Values() in DAX ?
Ans :- Both Returns distinct records but values returns Blank where as Distinct does not return blank.
The DISTINCT function allows a column name or any valid table expression to be its argument but the VALUES function
only accepts a column name or a table name as the argument.
Ans :- Max Only Work with Numerical value else return NULL or Zero whereas MAXA It takes Numerical , Text Or logical
values.
If the calculation is for numeric values then use MAX , if it is for non Numeric values then use MAXA.
https://community.powerbi.com/t5/Desktop/Index-and-year-month/td-p/569336
Ans :- This DAX functions can be worked as Filter context. If we use ALL that means it will remove all the filter that is
applied on this table or column. There wont be any effect even we apply any filter after calculations as well.
ALL_SELECTED :- Removes context filters from columns and rows in the current query , while retaining all other
context filtersor explicit filters. That means it will give value only which is being selected only in outer filters. Suppose in
current filter we will select Year -2018 and product XYZ i.e it will give us only 2018 XYZ value.
ALL_EXCEPT :- REMOVES all context filters on a table except filters that have been applied to the specified columns.
That means ALL EXCEPTS are going to return all the rows from tables except for those rows that are not affected by those
specified columns. It would clear all the filter except one particular column that is being applied. For example we have two
things in slicer product and country and we have given it like ALLEXCEPT ( table , Product column) ) . So it will ignore
whatever filter we will apply in country column. But if we will select anything in prodcut , the filter will apply accordingly.
Q. Can we add date diff column with new column in Direct Query ?
Ans :- it is not possible to use DATEDIFF function in calculated columns in DirectQuery mode. However, you can create a
measure instead.
Ans :- Dax helps you create new information from data already in your model with a series of Functions , operators and
constants. It will help you to get most out of your data.
Q. Filter in DAX ?
Ans :- It helps to filter out the data based on specific condition. So we can use it with CALCULATE functions.
Ex:- total_Sales = Calculate ( SUM[sales], FILTER(Country, Region_name = “AUS”))
Note :- By Adding logical Operator || We can add more Filter condition.
Q. If Condition in DAX ?
Ans :- IF (Condition , True part , False Part ) here False is optional.
Ex :- Gender = IF(emp[Gender] = “M” , “MALE” , “FEMALE”)
Q. Switch In DAX ?
Ans :- MonthName = Switch(EMP[Month] , 1, ‘JAN’ ,
2, ‘FEB’)
Q. MID in PowerBI ?
Ans :- It acts like a SubStr in SQL. This is one of the string functions that helps us to get part of string.
JobCode = MID(EMP[JobCode] , 1,3)
Q.Left in DAX ?
Ans:- JC_CHAR = Left(EMP(jobcode),3) __| -- Will Return 1 st three character from the column.
Q. REPT in DAX ?
Ans :- It is a DAX function which help us to repeat the given text or string no of times.
REPT_OP = REPt(EMP(JOBCODE), 1) if 1 it will be same as table column , pass 2 , will be copied twice and so on.
Q. EARLIER in DAX ?
Ans :- It is useful for Nested calculations where we want a certain value as input and produce calculations based on inputs.