Handling Division by ZERO errors in MDX Calculations

63
85955
Divided by Zero/ Null
Divided by Zero/ Null

Friends,

Handling Divided by Zero errors are very important in MDX. In other words we can call it as Divided by NULL errors in MDX. The error that show when you try to divide by Zero/Null is “1.#INF”. Lets see a small example.

If you see the below given query, it consists of a calculation which divided 1 with 0.

with member [Measures].[DivideByZeroError]
as 1/0
SELECT [Measures].[DivideByZeroError] on COLUMNS
from [Adventure Works DW]

The result of the above given query is 1.#INF as shown in the below pic.

Output of the calculation which divides 1 by 0
Output of the calculation which divides 1 by 0

Now I have written a calculation to check (Sales Amount)/(Discount Amount) for all products and the query looks like –

with member [Measures].[Sales to Discount]
as [Measures].[Sales Amount]/[Measures].[Discount Amount]
SELECT {[Measures].[Sales Amount],
[Measures].[Discount Amount],
[Measures].[Sales to Discount]} on COLUMNS ,
[Dim Product].[English Product Name].[English Product Name] on ROWS
from [Adventure Works DW]

IF you run the above query you can see many values coming as “1.#INF” as Discount Amount is either NULL or 0 for many products and PFB Screenshot of the same.

Divide By Zero Error
Divide By Zero Error

Lets see how can we make use of IIF condition to avoid these errors. The IIF Condition syntax in MDX is as given below.

IIF(condition,true,false) – If the condition is TRUE then first part will be executed else second provided in the iff condition. The query looks like below after applying IIF condition.

with member [Measures].[Sales to Discount]
as iif([Measures].[Discount Amount] = 0,null,[Measures].[Sales Amount]/[Measures].[Discount Amount])
SELECT {[Measures].[Sales Amount],
[Measures].[Discount Amount],
[Measures].[Sales to Discount]} on COLUMNS ,
[Dim Product].[English Product Name].[English Product Name] on ROWS
from [Adventure Works DW]

In the above query I am specifying that if Discount Amount is 0 then place NULL for the product in the calculated measure output else calculate the value. The output will look like this –

IIF Condition
IIF Condition

That’s it and Happy Coding Folks !

Regards,

Roopesh Babu V

 

63 COMMENTS

  1. CCTV Focus provides in-depth analysis of video surveillance technologies, covering IP camera systems and software solutions. It features detailed reviews of video management software (VMS), highlighting features such as object detection using artificial intelligence. The site offers ratings of surveillance system manufacturers and their products. A curated list of the top 10 video surveillance software options is available. The resource also includes analysis of various surveillance technologies, with attention to specialized AI functionalities within CCTV. The content is designed for both professional installers and business owners, providing information to assist in making informed decisions about security systems. The site’s guides cover camera selection, current challenges in video surveillance and advanced security protocols.
    [url=https://www.cctv-focus.com/]desktop surveillance software[/url]

  2. Форум предназначен для обсуждения вопросов, связанных с видеонаблюдением и безопасностью. Участники могут делиться информацией и опытом в области программного обеспечения для видеонаблюдения на ПК, совместимого с IP-камерами. Рассматриваются комплексные решения, VMS, CMS, а также технологии AHD и IP. Обсуждаются вопросы настройки, восстановления паролей камер, и применения ИИ-видеоаналитики. Отдельное внимание уделено применению интегрированной видеоаналитики на основе искусственного интеллекта, включая обнаружение объектов, распознавание автомобильных номеров и лиц, а также выявление признаков дыма и огня. Форум является площадкой для обмена знаниями и обсуждения актуальных тем в области видеонаблюдения. Здесь пользователи могут делиться своим опытом, задавать вопросы и находить решения для своих задач. Форум служит платформой для обмена знаниями и поиска решений в сфере видеонаблюдения. [url=https://securityvideo.ru/]видеоаналитика распознавание[/url]

  3. Guatemala has pledged a 40% increase in deportation flights carrying Guatemalans and migrants of other nationalities from the United States, President Bernardo Arevalo announced Wednesday during a press conference with US Secretary of State Marco Rubio.
    [url=https://kra-33-cc.ru]kra50 cc[/url]
    Guatemala has also agreed to create a task force for border control and protection along the country’s eastern borders. The force, composed of members of the National Police and army, will be tasked with fighting “all forms of transnational crime,” Arevalo said.
    [url=https://kra-35.ru]kra42 cc[/url]
    Foreign nationals who arrive in Guatemala through deportation flights will be repatriated to their home countries, Arevalo said, adding that the US and Guatemala would continue to have talks on how the process would work and how the US would cooperate.
    [url=https://kra-40-at.ru]kra44 at[/url]
    Arevalo also said that Rubio has voiced his support for developing infrastructure projects in the Central American nation. He added that his government would send a delegation to Washington in the coming weeks to negotiate deals for economic investments in Guatemala – which he said would incentivize Guatemalans to stay in their home country and not migrate to the US.

    Arevalo said Guatemala has not had any discussions about receiving criminals from the US as El Salvador’s president has offered. He also insisted his country has not reached a “safe third country” agreement with the United States, which would require migrants who pass through Guatemala to apply for asylum there rather than continuing to the US.
    kra39.at
    https://at-kra37.cc

  4. Wells such as Longhorn A — which for most operators would be economically worthless since they lack pipeline capacity to transmit any gas they produce — are a model for giving new life to aging wells. Bitcoin mining offers them a new revenue stream and, as one bitcoin mine operator wrote in a 2023 blog post, going off-grid comes with a suite of “superpowers,” including the ability to relocate quickly and to “operate permissionlessly.” Digital & Trend reports We validate arguments from both sides and provide empirical evidence for the extent and energy sources of Bitcoin mining in the U.S., based on data from 13 publicly listed mining companies that account for one-fourth of the total network hashrate as of the end of 2022. Using the grid average emission factors, we find that the carbon intensity of electricity consumed by the 13 miners included in our analysis of 397 gCO2 kWh is nearly equivalent to the U.S. grid average of 387 gCO2 kWh. Furthermore, we find that the annual emissions of 7.2 MtCO2 caused by the 13 analyzed publicly listed miners in the U.S. alone surpass the carbon emissions of the State of Vermont.
    https://avader.org/page/business-services/https-changehero-io-buy-btc
    Cronos (CRO) is the utility token for the Crypto exchange. CRO can be used to pay fees on the platform and also staked to qualify for various benefits. It saw significant growth last year, partly reflecting Crypto’s aggressive promotional activities. Like most of the crypto industry, CRO has struggled so far in 2022. This feedback is never shared publicly, we’ll use it to show better contributions to everyone. Extensive list of supported cryptocurrencies In 2019 Crypto began to launch more services. This included crypto-to-crypto exchange services with the aiming of being a more broad one-stop shop for crypto users that would target the profitable “crypto trader” demographic. In the same year, the company began offering centralized crypto borrowing and lending services in a similar vein to Celsius and BlockFi. These services were called Crypto Earn and Crypto Credit. In 2019, Crypto cards begin shipping to the United States.

  5. Как зарегистрироваться в личном кабинете [url=https://mostbet-wza1.xyz/]mostbet[/url], как пополнить счет, сделать ставку и выиграть деньги на популярном букмекерском сайте.

  6. Заказать такси на курорт и оптимизировать расходы на жд вокзале Симферополя — задача, которая требует ответственного подхода.

    Прежде всего, стоит заранее проанализировать предложениями различных сервисов, чтобы выбрать наиболее удачный вариант. Многие приложения и сайты предоставляют скидки для новых клиентов или акции в определенное время суток.
    https://tratatur.ru/price/taxi-simferopol-simeiz

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

    И, конечно, бронируйте такси до момента поездки — это не только понизит ваши деньги, но и освободит от лишнего стресса в дороге.

  7. https://mostbet-wdz6.top/ о последних обновлениях и возможных блоках доступа к сайту букмекерской конторы Мостбет через актуальное зеркало для удобного доступа к ставкам и функционалу сайта.

  8. Фонбет промокод: MAX777, используйте его при регистрации аккаунта. Новые пользователи могут активировать бонус и получить бездепозитный фрибет до 15 000 рублей. Воспользоваться бесплатно промокодами «Фонбет» для получения подарочной ставки или другого бонуса можно во время создания аккаунта на официальном сайте букмекерской конторы, а также после активации личного кабинета. Действующие промокоды могут давать зачисление кэшбэка на депозит, бесплатное пари и т.п.

    промокод для фонбет

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

  10. https://mostbet-wdt5.top/ – как зайти на официальный сайт Мостбет и начать делать ставки на спорт с высокими коэффициентами и удобным интерфейсом.

  11. Желаете скачать Mostbet и начать делать ставки на спортивные события с удобного мобильного устройства? Узнайте, как это сделать быстро и просто в нашей статье!

  12. Выигрывай реальные деньги в лучших казино! Топ слотов, акции, стратегии для победы! Подписывайся
    Игровые автоматы: фишки, стратегии, бонусы! Заработай с нами! Только честные обзоры.
    https://t.me/s/official_1go_1go/670

  13. На сайте мостбет казино вы найдете актуальное зеркало, которое позволит с легкостью получить доступ к игровым автоматам и другим азартным развлечениям.

  14. Когда речь идет о ремонте, выбор правильной краски — это один из самых важных этапов. Строительные краски не только придают вашему интерьеру стильный вид, но и защищают поверхности от внешних воздействий. Мы предлагаем широкий ассортимент высококачественных строительных красок, которые удовлетворят потребности как профессиональных строителей, так и домашних мастеров – [url=https://money.bestbb.ru/viewtopic.php?id=1842#p8662]краска вгт для внутренних работ.[/url]

  15. Приветствую, уважаемые форумчане! Хочу рассказать о важности и необходимости профессионального ухода за деревьями, особенно в условиях городской среды. Речь пойдет об арбористике – комплексе мероприятий по уходу, лечению и, при необходимости, удалению деревьев.

    Многие считают, что уход за деревьями ограничивается поливом и обрезкой сухих веток. Однако, современная арбористика – это целая наука, включающая в себя диагностику заболеваний, укрепление деревьев, защиту от вредителей и формирование кроны – [/color][url=https://obovsem.myqip.ru/?1-5-0-00000616-000-0-0-1750659593]Спил деревьев частями[/url

  16. Инновационный бот для обработки фото в Telegram сочетает простоту, доступность и впечатляющий результат. Загрузите фотографию, и через 20 секунд получите готовый результат. Нейросеть аккуратно снимает одежду и создаёт реалистичное тело.

    Не требуется регистрация или установка программ – бот работает прямо в Telegram. Обработка двух снимков обойдётся в 150 рублей. Вы также можете выбрать пакетные предложения: 10 фото за 630 рублей или 50 снимков за 2800 рублей.

    Полная безопасность и анонимность обеспечены. Высокое качество результата гарантировано. Готовы попробовать? [url=https://protrud.com/революция-в-обработке-изображений-пр/]Революция в обработке изображений: преимущества онлайн нейросетей для фотографий[/url]

  17. In case you don’t want to be concerned in a prolonged discussion, get rid of the idea of speaking about the political situation. Many Ukrainian women possess a natural magnificence that manifests itself not only via their bodily look but in addition within the delicate manner they carry themselves as well as within the charm they carry into any room or scenario. Within the Russian courting scene, there’s a significant emphasis on bodily look. In Rome for example, there’s Termini Train Station where I bought pickpocketed, and Bus 64 AKA the Pickpocket Express. Also, it’s necessary to grasp that ladies on such websites are assured to be a minimum of 18 years old, so there’s nothing to fret about. Reputation: Look for reputable websites with positive opinions and testimonials. There are various Slavic ladies relationship websites on the internet, and the range can really feel overwhelming. These worldwide marriage agencies interview each single Ukrainian lady who needs to add their relationship profile to the database.

    Next up, check out their security measures, like profile verification and secure communication channels. For example, some Russian families might like their child to wed a man who has a specific occupation or profession path. They take pride in offering for their households and understand the importance of training, profession improvement, and monetary safety. This emphasis on conventional gender roles creates compassionate and loving wives who take pride in offering for his or her households. Ukrainian ladies make wonderful wives. Secondly, Americans believe that Ukrainian women are extra standard than their fellow females and would make excellent wives. However, this does not necessarily reflect actuality, given the increase in literacy charges amongst ladies, which has allowed them more opportunities to pursue higher training or work abroad if they wish. The Latvian linguist Jānis EndzelÄ«ns thought, however, that any similarities amongst Baltic and Slavic languages resulted from intensive language contact, i.e. that they weren’t genetically extra closely associated and that there was no widespread Proto-Balto-Slavic language. Also, because Ukraine stays relatively conservative compared to many different elements of Europe, these ladies tend towards more conventional gender roles, similar to taking on home duties within the home and more.

    The home loans, utilized by 2.Four million returning veterans, would assist to develop America’s suburban panorama and private wealth. Another stereotype is that, as in other Eastern European international locations, Ukrainians have “old-fashioned” gender roles, the place women are expected to stay at home while males go out to work. Stay patient and supportive throughout moments of loneliness or longing for physical closeness; do not forget that distance is temporary while love is enduring. They value laborious work and dedication to these they love and take great pleasure in making sure everyone is taken care of. Czech ladies are great partners for individuals who appreciate a progressive outlook combined with strong family values. Ukrainian tradition emphasizes the significance of marriage and family life, which is instilled in many young Ukrainian ladies from an early age. By immersing your self in their traditions, values, and means of life, you present genuine interest and respect for who they are as people. In actuality, Ukrainian girls are strong, impartial individuals who know what they want and aren’t afraid to speak their [url=https://www.pinterest.com/charmdater/]charmdate[/url] minds. This stereotype stems from a few isolated incidents and should not outline an entire inhabitants of diverse people with distinctive goals and aspirations.

    You wish to showcase your finest self whereas being real and approachable when chatting onn courting web sites and apps. By understanding their allure, navigating cultural disparities with sensitivity, dispelling misconceptions, approaching them with sincerity and respect while maintaining a long-distance relationship thoughtfully – you possibly can have a fulfilling and lasting partnership with a Ukrainian girl that transcends borders. Communication is important in any relationship however significantly essential when dating somebody from another tradition. Keep in mind that communication is key in any relationship, especially when there are cultural variations at play. With regards to approaching relationship with a Ukrainian girl, authenticity is key. The earliest clear reference to the Avar ethnonym comes from Priscus the Rhetor (420s-after 472), who recounts that in c. When it comes to Ukrainian ladies, there are several misconceptions and stereotypes that always overshadow the truth of who they truly are. Getting to know her as an individual somewhat than projecting these misconceptions onto her will lead to a extra significant connection based mostly on authenticity and respect. It not only strengthens your relationship but additionally deepens your connection on a more profound level. Having similar values or beliefs will enable you form a strong connection along with your man and ensure your relationship stands the check of time.

  18. Its like you read my mind! You appear to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead of that, this is magnificent blog. An excellent read. I will definitely be back.
    Limousine service near me

  19. Июль 2025 года, BlackSprut Marketplace Официально обьявляет актуальные ссылки для входа на Marketplace.

    bs2best at

    Будь с нами, с BlackSprut!

  20. Всем привет, мои дорогие сериаломаны!

    Хочу поделиться с вами своими невероятно позитивными впечатлениями от просмотра нового турецкого сериала! Честно говоря, давно не испытывала такого восторга. С первых минут сериал захватил меня полностью, и я не могла оторваться от экрана до самой последней серии. Что меня особенно поразило? Прежде всего, это атмосфера! Она пропитана теплом, уютом и какой-то непередаваемой искренностью. Сюжет развивается неспешно, позволяя полностью погрузиться в жизнь героев, понять их мотивы и чувства. Никакой гонки, никакой спешки – просто наслаждаешься каждым моментом – [url=https://moturk.ru/]смотреть турецкий сериалы[/url]

  21. Повысьте эффективность своего производства с помощью наших приводных устройств! Наши инновационные устройства позволят вам значительно снизить расходы на электроэнергию,
    увеличить производительность оборудования и снизить износ механизмов. Благодаря нашиему оборудованию вы сможете значительно увеличить производственные мощности и улучшить качество выпускаемой продукции – [url=https://mymoscow.forum24.ru/?1-6-0-00030203-000-0-0-1750853646]Частотный преобразователь 11 кВт[/url]

LEAVE A REPLY

Please enter your comment!
Please enter your name here

five + 4 =