Dax если ошибка

 Содержание статьи: (кликните, чтобы перейти к соответствующей части статьи):

  • DAX функция ERROR
  • DAX функция IFERROR (если ошибка)
  • DAX функция ISERROR

Антон Будуев Приветствую Вас, дорогие друзья, с Вами Будуев Антон. В этой статье мы рассмотрим несколько функций в Power BI и Power Pivot, которые так или иначе обрабатывают возникающие во время вычислений в DAX, ошибки. И это функции ERROR, IFERROR и ISERROR.

Для Вашего удобства, рекомендую скачать «Справочник DAX функций для Power BI и Power Pivot» в PDF формате.

Если же в Ваших формулах имеются какие-то ошибки, проблемы, а результаты работы формул постоянно не те, что Вы ожидаете и Вам необходима помощь, то записывайтесь в бесплатный экспресс-курс «Быстрый старт в языке функций и формул DAX для Power BI и Power Pivot».

 

DAX функция ERROR в Power BI и Power Pivot

ERROR () — останавливает выполнение DAX кода и выводит заранее определенную пользователем ошибку (предупреждение).

Синтаксис: ERROR («Текст ошибки»)

Пример: в Power BI имеется исходная таблица с перечислением товаров и их количеством

Исходная таблица

Суть задачи: создать такую меру, чтобы она всегда вычисляла общее количество товара и пользователь не мог наложить никаких фильтров на это вычисление. Если пользователь накладывает фильтры, нужно остановить вычисление меры и в Power BI Desktop выдать пользователю ошибку (предупреждение).

Общее количество можно рассчитать при помощи DAX функции SUM:

Общее Количество Товара = SUM ('Товары'[Количество])

Данная формула действительно сможет посчитать общее количество товара, но она также легко подвержена пользовательским фильтрам, что по условию задачи нам не нужно:

Пользовательская фильтрация количества товара

Тогда мы можем изменить формулу выше и сумму рассчитать под следующим условием: если наложен какой-либо фильтр, то выдать пользователю предупреждение, если фильтра нет, то рассчитать количество.

Все это легко решается при помощи функций IF (условия «если») и ISFILTERED (проверяет на наличие фильтров):

Общее Количество Товара = 
IF(
    ISFILTERED('Товары'[Товар]);
    "ФИЛЬТРОВАТЬ ТОВАРЫ НЕЛЬЗЯ!";
    SUM('Товары'[Количество])
)

Получившаяся формула вполне рабочая, если мы выберем какой-либо товар, то нам действительно выйдет предупреждение:

Результат работы DAX формулы

В принципе, мы задачу практически решили. Но, можно пойти еще дальше и при пользовательском фильтре не то чтобы просто вывести предупреждение, а вообще остановить работу DAX формулы и тем самым действительно обратить внимание пользователя к ошибке.

И это как раз таки можно реализовать при помощи функции ERROR, прописав внутри нее наш текст предупреждения, и вставив ERROR заместо текста предупреждения в формуле выше:

Общее Количество Товара = 
IF(
    ISFILTERED('Товары'[Товар]);
    ERROR("ФИЛЬТРОВАТЬ ТОВАРЫ НЕЛЬЗЯ!");
    SUM('Товары'[Количество])
)

Тогда, если пользователь наложит фильтр, то DAX формула остановит свою работу:

Функция ERROR остановила работу формулы

И при нажатии на визуализации в Power BI на ссылку «См. подробности», выйдет текст самого предупреждения, который мы прописывали в ERROR:

Вывод предупреждения функции ERROR

Если убрать все фильтры, то, соответственно, формула рассчитает общее количество товаров и ни каких предупреждений от ERROR не будет.

DAX функция IFERROR (если ошибка) в Power BI и Power Pivot

IFERROR () — если ошибка. Производит вычисление выражения и если во время вычисления возникла ошибка, то функция выводит значение из второго параметра, если ошибок нет, то возвращается результат вычисления самого выражения.

Синтаксис: IFERROR (Выражение; Значение Если Ошибка)

Пример формулы 1: IFERROR (6 / 2; BLANK() ) 
Результат: 3

В итоге возвратился результат вычисления самого выражения, так как само выражение «6 / 2» вычисляется без ошибок и равно 3.

Пример формулы 2: IFERROR (6 / 0; BLANK() ) 
Результат: пусто

Так как на 0 делить нельзя, то результатом вычисления выражения будет ошибка и в этом случае IFERROR выведет значение из второго параметра, где в нашем случае стоит функция BLANK, которая, в свою очередь, выводит пустое значение.

То есть, функцией IFERROR можно обрабатывать ошибки в формулах, где возможно деление на 0. Но, кроме этого, можно при помощи нее застраховываться и от любых других ошибок, возникающих при выполнении формул в DAX.

DAX функция ISERROR в Power BI и Power Pivot

ISERROR () — относится к информационным функциям DAX. Она выводит значение TRUE (Истина), если значение, входящее в ее параметр вычисляется с ошибкой, а также, значение FALSE (Ложь), если ошибок нет.

Синтаксис: ISERROR (Значение)

Пример формулы 1: ISERROR (6 / 2)
Результат 1: FALSE (Ложь)

Пример формулы 2: ISERROR (6 / 0)
Результат 2: TRUE (Истина)

В первой формуле ISERROR выдала значение FALSE (Ложь), потому что выражение «6 / 2» вычисляется без ошибки. Тогда как, во втором случае выражение «6 / 0» вычисляется с ошибкой и поэтому ISERROR выдала значение TRUE (Истина).

Если ISERROR дополнить функцией условия «если» IF, то получится полный аналог DAX функции, которую мы рассматривали выше — IFERROR:

IFERROR = 
IF (
    ISERROR (Выражение);
    "Значение Если Ошибка"
    Выражение
)

 
На этом, с разбором функций обработок ошибок в Power BI и Power Pivot, все.

Пожалуйста, оцените статью:

  1. 5
  2. 4
  3. 3
  4. 2
  5. 1

(5 голосов, в среднем: 5 из 5 баллов)

[Экспресс-видеокурс] Быстрый старт в языке DAX

    Антон БудуевУспехов Вам, друзья!
С уважением, Будуев Антон.
Проект «BI — это просто»

Если у Вас появились какие-то вопросы по материалу данной статьи, задавайте их в комментариях ниже. Я Вам обязательно отвечу. Да и вообще, просто оставляйте там Вашу обратную связь, я буду очень рад.

  Также, делитесь данной статьей со своими знакомыми в социальных сетях, возможно, этот материал кому-то будет очень полезен.

 
Понравился материал статьи?
Избранные закладкиДобавьте эту статью в закладки Вашего браузера, чтобы вернуться к ней еще раз. Для этого, прямо сейчас нажмите на клавиатуре комбинацию клавиш Ctrl+D

DAX Guide

A-ZGroupsSearch

 

IFERROR DAX Function (Logical) Not recommended

Returns value_if_error if the first expression is an error and the value of the expression itself otherwise.

Syntax

IFERROR ( <Value>, <ValueIfError> )

Parameter Attributes Description
Value

Any value or expression.

ValueIfError

Any value or expression.

Return values

Scalar A single value of any type.

A scalar of the same type as Value

» 3 related functions

Examples

--  IFERROR detects if the first argument produces an error.
--  In that case, it returns the second argument, without 
--  erroring out.
DEFINE
MEASURE Sales[Year Value unprotected] = 
    VAR CurrentYear = SELECTEDVALUE ( 'Date'[Calendar Year] )
    RETURN VALUE ( CurrentYear )
MEASURE Sales[Year Value] = 
    VAR CurrentYear = SELECTEDVALUE ( 'Date'[Calendar Year] )
    RETURN 
        IFERROR (
            INT ( VALUE ( CurrentYear ) ),
            INT ( VALUE ( RIGHT ( CurrentYear, 4 ) ) )
        )
EVALUATE
    SUMMARIZECOLUMNS ( 
        'Date'[Calendar Year], 
        // If you uncomment the following line, the query generates an error
        // "Year Value unprotected", [Year Value unprotected],
        "Year Value", [Year Value]
       )
ORDER BY [Calendar Year]
Calendar Year Year Value
2005-01-01 2,005
2006-01-01 2,006
2007-01-01 2,007
2008-01-01 2,008
2009-01-01 2,009
2010-01-01 2,010
2011-01-01 2,011

Related functions

Other related functions are:

  • IF
  • ISERROR
  • DIVIDE

Last update: May 26, 2023   » Contribute   » Show contributors

Contributors: Alberto Ferrari, Marco Russo, Kenneth Barber

Microsoft documentation: https://docs.microsoft.com/en-us/dax/iferror-function-dax

2018-2023 © SQLBI. All rights are reserved. Information coming from Microsoft documentation is property of Microsoft Corp. » Contact us   » Privacy Policy & Cookies

To generate formulas and expressions in Excel data models for Power BI, Analysis Services, and Power Pivot, Data Analysis Expressions (DAX), a group of functions and operators, can be combined. Data Analysis Expression is a feature of the Power BI toolset that enables business analysts to maximize the value of their datasets. These expressions make the process of creating reports faster and more enjoyable for the data analyst.

DAX IF Functions

Logical IF functions, which are used to combine many conditions and decide if a condition is true or not, enable the introduction of decision-making. Logical functions provide details about the values or sets in an expression when they are applied to it. Let’s validate these functions on a sample library supplies dataset. It can be seen as follows-

Dataset

Dataset

Apply the following queries by adding a New column in the model.

New-column

DAX IF

Validates a condition and, if TRUE, returns one value; else, it returns another.

Syntax: IF(<logical_test>, <value_if_true>[, <>])

  • logical_test: Anything that may be evaluated to either TRUE or FALSE.
  • value_if_true: The result that is returned when the logical test returns TRUE.
  • value_if_false: The value that is returned if the logical test returns FALSE (optional). BLANK is returned if it is left out.

In the following example, we are checking if the client is Delhiite or not, based on the name of the Client State.

Example: Column = IF(‘SLS Order Detials_Master'[Client State]= “New Delhi”, “Resident”, “Non-resident”)

The column gets added to the dataset as shown below,

dax-if-function-example

DAX IF.EAGER

Validates a condition and, if TRUE, returns one value; else, it returns another. The execution plan is eager, and regardless of the condition expression, it always performs the branch expressions.

Syntax: IF.EAGER(<logical_test>, <value_if_true>[, <value_if_false>])

  • logical_test: Anything that may be evaluated to either TRUE or FALSE.
  • value_if_true: The result that is returned when the logical test returns TRUE.
  • value_if_false: The value that is returned if the logical test returns FALSE (optional). BLANK is returned if it is left out.

In the following example, we are checking if the client is Delhiite or not, based on the Client’s Pin code.

Example: Column1 = IF.EAGER(‘SLS Order Detials_Master'[Client Pin Code]= “110003”, “Resident”, “Non-resident”)

The column gets added to the dataset as shown below,

If.Eager-function-example

DAX IFERROR

DAX IFERROR returns the outcome of the expression itself unless the expression returns an error, in which case it returns a specified value.

Syntax: IFERROR(value, value_if_error)

  • value: Any term or value.
  • value_if_error: Any term or value.

Example: Column2 = IFERROR(345/0,345) 

The column gets added to the dataset as shown below,

IfError-function-example

Last Updated :
23 Jan, 2023

Like Article

Save Article

Evaluates an expression and returns a specified value if the expression returns an error. Otherwise, returns the value of the expression itself.

Syntax:

IFERROR ( <Value>, <Value_If_Error> )

Description:

S no. Parameter Description
1 Value Any value or expression.
2 Value_If_Error Any value or expression, give error message here.

Let’s get started-

Following these steps-

Step-1: Create measure and write below expression in measure, here we creating an error situation to adding String and Number value.

Measure in Power Bi

Measure in Power BI

Step-2: Now take one Card visual into Power BI page and drag measure over there.

Conversion Error in Measure

Conversion Error in Measure

As you saw, it returns an error ‘can not convert Text to Number’, now we handle the error with some messages.

Step-3: Create other measure and write below expression in measure.

IFERROR_Measure = IFERROR("A"+1,"Wrong Input")

IFERROR-DAX

IFERROR – DAX

Step-4: After this drag measure into Card visual, it returns the given error message instead of conversion error.

IFERROR DAX Example

IFERROR DAX Example

If expression not return any error, it returns the value of expression, let’s see-

IFERROR_Measure_2 = IFERROR(1+1,"Wrong Input")

IFERROR - DAX

IFERROR – DAX

Hope you enjoyed the post. Your valuable feedback, question, or comments about this post are always welcome or you can leave us message on our contact form , we will revert to you asap.

Recommended Power BI Post:

ALLEXCEPT

UNION

DATATABLE

ALLSELECTED

ALL

ADDCOLUMNS

IFERROR Function is a Power BI DAX Logical Function that evaluates an expression and returns a specified value, If the expression returns an error else returns the value of the expression itself.

It returns a scalar of the same type as value.

SYNTAX

IFERROR(value, value_if_error)

value is any value or expression.

value_if_error is any value or expression that is used to specify a value or expression that you want to see in output, if you get an error.

Lets look at an example of IFERROR function.

IFERROR Function to trap and handle an error

In following Dax Measure, IFERROR function trap an error and returns an alternate output value as a message .

Here we have provided an expression 1/0 to IFERROR function that produce a divide by zero error, and IFERROR Function trap this error and returns a second argument (value_if_error) value that is “Divided By Zero Error” .

Value = IFERROR(1/0, "Divided By Zero Error")

Lets drag the Value measure onto Card visual to see the output.

Here you can see, it returns a second argument value that is a message as expression evaluates an error, and IFERROR function trap this error.

IF IFERROR function when no error occurred

If no error occurred then IFERROR Function returns the value of expression itself.

Lets modify the above measure as given below.

Now we have taken an expression as 10/10, that is valid expression and will not give any error so IFERROR function just returns the value of expression as output.

Value = IFERROR(10/10, "Divided By Zero Error")

Lets see the output of measure, drag the measure onto card visual.

It returns the expression value that is 10/10 =1.

Lets look at one more example.

Here we have a dataset that includes an item and their Quantity and Price.

ID      Item           Price  Quantity

1 HP 500 0
2 SAMSUNG 200 null
3 ACER 500 null
4 ACER 780 9
5 DELL 1200 5
6 APPLE 5680 70

Now we have to create a measure to calculate per quantity price that will be a (Total price) /(Total Quantity) for an individual items.

As you can see, some of quantity value is null or zero, that can produce infinity or divide by zero error.

Lets create a measure to calculate a Per Quantity Price.

PER_QUANTITY_PRICE = (SUM(PriceTbl[Price])/SUM(PriceTbl[Quantity])

To see the output of measure PER_QUANTIY_PRICE, just drag it in table visual.

As you can see, for last two records ,it returns infinity.

To trap and handle such error, IFERROR function can be used as shown below.

Lets create another measure that uses IFERROR Function

PER_QUANTITY_PRICE_With_IFERROR = 
IFERROR(SUM(PriceTbl[Price])/SUM(PriceTbl[Quantity]),0)

Lets see the ouput of PER_QUANTITY_PRICE_With_IFERROR measure by dragging it to next of previous measure in table visual.

You can see, For last two records IFERROR function gives 0 value.

Also Read..

SQL Basics Tutorial SQL Advance Tutorial SSRS Interview Q & A
SQL Create table SQL Server Stored Procedure Create a New SSRS Project List Of SQL Server basics to Advance Level Interview Q & A
SQL ALTER TABLE SQL Server Merge Create a Shared Data Source in SSRS SQL Server Question & Answer Quiz
SQL Drop SQL Server Pivot Create a SSRS Tabular Report / Detail Report
….. More …. More ….More
Power BI Tutorial Azure Tutorial Python Tutorial SQL Server Tips & Tricks
Download and Install Power BI Desktop Create an Azure storage account Learn Python & ML Step by step Enable Dark theme in SQL Server Management studio
Connect Power BI to SQL Server Upload files to Azure storage container SQL Server Template Explorer
Create Report ToolTip Pages in Power BI Create Azure SQL Database Server Displaying line numbers in Query Editor Window
….More ….More ….More

 6,132 total views,  1 views today

IFERROR Evaluates an expression and returns a specified value if the expression returns an error; otherwise returns the value of the expression itself.


Syntax

IFERROR(value, value_if_error)

Parameters

Value – Any value or expression.

Value_if_error – Any value or expression.

Return Value

A scalar of the same type as value


Reference Data

https://docs.microsoft.com/en-us/dax/dax-function-reference

DAX Functions / Logical Functions / IFERROR

IMPORTANT: You can read the official documentation that Microsoft has on this topic from the following link (url).

If you haven’t read the first two posts (Part 1 | Part 2) in this series yet, I welcome you to do so before reading this one.

I also recommend that you check out this post on Query Error Auditing so you get a better understanding of what types of errors you can find in Power BI / Power Query.

This is a post on how to use error handling, similar to an IFERROR in DAX and Excel, but for Power Query (using its M language).

How does Error handling works in Excel & DAX?

In Excel and in DAX we have the IFERROR function which works like this:

=IFERROR( value, value_if_error)

Taken directly from the official DAX documentation:

Evaluates an expression and returns a specified value if the expression returns an error; otherwise returns the value of the expression itself.

It’s a pretty simple and straightforward function in DAX and Excel, where you can enter your formula in the “value” parameter and then, if you get an error from it, you can define what should be the output value in the “value_if_error” parameter.

The whole idea is that you can “catch” an error and use a different value when it finds an error.

How does Error handling works in Power BI / Power Query?

In Power Query the code is a bit different. Let’s see it in action and then talk more about it.

Imagine that we have an Excel workbook with a table like this

image:

What we would like to create is a new column that should multiply the values from the [Price] and [Amount] columns to create a new Subtotal column.

One caveat, as you can probably see, is that this spreadsheet has some cells with errors on the [Price] column. In the event that we find an error on the Price column, we need to use the value from the [List Price] instead of the [Price] value.

The first thing that we need to do is import that table from Excel. If you’d like to follow along, you can download the workbook by clicking the button below:

Importing data from the Excel Workbook

I’ll be using Power BI Desktop for this, but you can use Excel as well.

The first thing that we need to do is select the Excel connector and connect to our file:

image

and once you get the “Navigator” window, you can select the table that reads “Sample”:

image

Notice how there’s a bunch of errors in that [Price] column just in the preview. Let’s hit the “Edit” button so we can go to the Power Query Editor Window.

Using error handling in Power BI /Power Query

Now that we have our data in the Power Query Editor window:

image what we want to do is create a Custom Column, so we simply go to the “Add Column” menu and hit on “Custom Column”.

In there, we try do create a simple column that will multiply the [Price] column by the [Amount] column:

image

and as you can see, our [Subtotal] column has some errors.

We know that in Excel and DAX you can use IFERROR, but what can you use in Power Query ?

For Power Query, we need to hit modify that Custom Column code (just click the gear icon next to the Added Custom step) and add the following pieces to it:

image

try [Price]*[Amount] otherwise [Amount]*[List Price]

We need to use the keywords “try” and “otherwise”. It’s pretty easy to read, but it just says to try and evaluate the expression ([Price] * [Amount]) and if that gives an error, use the expression defined after the otherwise statement.

The result of that will look like this:

image

pretty simple! almost as simple as the IFERROR function in DAX and Excel where intellisense does explain you a bit how to use that function, but in Power Query you need to understand how this works in order to use it. Is nowhere in the User Interface of Power Query, so you need to write this code manually.

Understanding Errors

The workbook sample that I’m using is fairly simple. I’ve had experiences where some users / customers absolutely need to know when a specific error is found from an Excel Workbook.

What happens with Power Query is that it just flags any errors found as “Error” but, what if you needed to know WHY it shows as an error?

Let’s go back to our initial load of the file. Remember that in most cases Power Query will automatically try to add a “Changed Type” step, so what if we remove that step?

image

Well, I removed the step and I’m still seeing the errors and that’s because the error wasn’t triggered by a data type conversion, but rather it’s a source error, meaning that the error comes directly from the Excel Workbook.

In Workbook with vast amounts of rows, it’s hard to tell if there are any errors at all and doing a “Replace Errors” will not tell us why those errors occurred. We NEED to know what is the error from the source because we want to handle each type of error differently.

Error Message and Error Reason

To figure out what’s the reason why there’s an error, we need to use the “try” statement again.

image

Note how I only use “try” and not the “otherwise” statement. This will give me a new column with record values. We can expand those records like this:

image

the most important field from those records it’s the “Error” field which can be either a null or a record value:

image

and after expanding that column and deleting some others that we don’t need, I end up with this:

image

I’ve highlighted the most important field after this whole process which is the “Message” which tells me exactly the reason why this is an error.

I can later use this to my advantage and target specific errors differently or get a report of ALL the errors found on a series of files that my department / group uses. This is extremely helpful if you’re trying to validate everything and make sure that we don’t have any errors at the source.

Don’t forget that these same principles work for both Step and cell Value level errors.

Понравилась статья? Поделить с друзьями:
  • Dawn of war soulstorm ошибка инициализации системы
  • Dayz выдает ошибку msvcp100 dll
  • Dawn of war soulstorm ошибка инициализации видеокарты
  • Dayz zombiemaniya ошибка
  • Dawn of war apocalypse mod критическая ошибка