Using NULLIF to divide by zero - sql

This is the error I'm receiving below:
Divide by zero error encountered.
Warning: Null value is eliminated by an aggregate or other SET operation.
Having looked around at solutions it looks like I need to use NULLIF or ISNULL, I'm just unsure as to how to include it within the line below.
select
min(round(OnCallTime*100/TotalTime,1)) as total
I'm using SQL Management Studio 2012

Use NULLIF in denominator like below:
select
min(round((OnCallTime*100/NULLIF(TotalTime,0)),1)) as total
So, whenever TotalTime is zero, it'll be replaced by NULL and you will not get the error of Division by Zero.

So in the event TotalTime=0 what do you want to display?. I suggest NULL since divide by zero is not defined?.
You can write the query as follows
select
min(round(
(OnCallTime*100)
/ (case when TotalTime =0 then null else TotalTime end)
,1
)
) as total

use coalesce() function
select
min(round(OnCallTime*100/coalesce(TotalTime,1),1)) as total

use coalesce() which return 1st non null value
select min(round((OnCallTime)*100/coalesce(TotalTime,1),1)) as total

Related

SUM of database function returns much higher value than actual SUM

I have a database function that I am able to get the correct results from, but when I try to use SUM to total the results it returns a much higher value.
SELECT
SUM([DATABASE].[dbo].[fn_GetCharges]([TABLE1_DATE],[TABLE1_CUST],[TABLE1_SITE],[TABLE1_SERV])) AS [GROSS_REVENUE]
FROM [DATABASE].[dbo].[TABLE1]
WHERE
[TABLE1_ROUT] = '1234'
AND [TABLE1_DATE] = '2018-05-08'
This returns a SUM value of about 15,740.
If I remove the SUM and GROUP BY the function then it shows each of the returned values, which I manually totalled to about 750.
I'm using Microsoft SQL Server 2014.
We don't know what is in your function, but you could probably output your raw data first and then sum it next.
;WITH cte AS (
SELECT
[DATABASE].[dbo].[fn_GetCharges]([TABLE1_DATE],[TABLE1_CUST],[TABLE1_SITE],[TABLE1_SERV]) AS [GROSS_REVENUE]
FROM [DATABASE].[dbo].[TABLE1]
WHERE
[TABLE1_ROUT] = '1234'
AND [TABLE1_DATE] = '2018-05-08'
GROUP BY whatever_you_grouped_by_that_gave_correct_results
)
SELECT SUM(gross_revenue) AS gross_revenue
FROM cte
Wondering if you used group by clause in the query since I don't see one posted.
Group By (columns) Having (condition). What you specified in the 'where' goes in the 'Having' clause

SQL: select average of varchar

I would like to make a report that will show the average grade for different tasks.
I am having trouble with how to get the averages. I need to figure out how to convert the grades to floats so that I can take the averages. The grades sometimes have non-numeric or null values, although most values look like "2.0" or "3.5". I can exclude anything that is non-numeric.
This is what I have so far:
Select
GradingScores.task As task,
Avg(Cast((SELECT GradingScores.score WHERE GradingScores.score LIKE '%[^0-9]%')As float)) As averages
From
GradingScores
I am using FlySpeed SQL Query.
You could try using IsNumeric
Select
GradingScores.task As task,
Avg(Cast(GradingScores.score as float) As averages
From
GradingScores where IsNumeric(GradingScores.score) = 1
Just simply convert() and use isnumeric() function in T-SQL
select avg(convert(float,score))
from GradingScores
where isnumeric(score)=1
here's what worked for me:
SELECT AVG(CAST(columnName AS FLOAT)) FROM tableName;

Why are my SQL SUMs not coming back NULL when they include NULL values?

I use a CTE to calculate spans of time in a log as shown in this fiddle:
http://www.sqlfiddle.com/#!3/b99448/6
Note that one of the rows has a NULL value because that is the most recent log entry and no calculation could be made.
However, if I SUM these results the NULL is being treated as a zero:
http://www.sqlfiddle.com/#!3/b99448/4
How can I get this to stop ignoring NULL values?
I would expect the sum to be NULL since it is adding a NULL value.
The aggregation functions ignore NULL values. They are not treated as 0 -- the distinction is more important for AVG(), MIN(), and MAX(). So, SUM() only returns NULL when all values are NULL.
If you want to get NULL back, here is a simple expression:
select (case when count(*) = count(a.DateTimeChangedUtc) and
count(*) = count(b.DateTimeChangedUTC)
then SUM(DATEDIFF(SECOND, a.DateTimeChangedUtc, b.DateTimeChangedUTC))
end) AS TimeSpentSeconds
This returns NULL if either argument is ever NULL.

Calculating Percentage when Row can contain 0

I have previously asked the following question: Calculating percentage within the SQL
Now i was lucky enough to get a great answer however in my question i did not take into account that my rows could contain zero.
The questions row where simple:
select
Number_of_Calls,
Number_of_Answered,
((Number_of_answered/Number_Of_Calls)*100) as answer_percent,
Date
from table Where Date BETWEEN '2012-09-10' AND '2012-09-11'
However Number_of_answered could be zero (if our company did not answer the calls) so if i want the full number in percentage how do i take 0 into account?
By the way. The database that we use is an Oracle database with PL SQL
The nullif function can be used to return null if the divisor is zero. When SQL encounters a null divisor it forces the entire equation to return null, preventing your error from occurring.
select
Number_of_Calls,
Number_of_Answered,
((Number_of_answered/nullif(Number_Of_Calls,0))*100) as answer_percent,
Date
from table Where Date BETWEEN '2012-09-10' AND '2012-09-11'
If you would like to exclude null percentages use the following SQL:
select * from(select
Number_of_Calls,
Number_of_Answered,
((Number_of_answered/nullif(Number_Of_Calls,0))*100) as answer_percent,
Date
from table Where Date BETWEEN '2012-09-10' AND '2012-09-11') alias
where answer_percent is not null;
Case when Number_Of_Calls = 0
THEN 0 --or your desired value, maybe 100
else (Number_of_answered/Number_Of_Calls)*100
END as answer_percent
i think you mean "Number_Of_Calls" could be zero (thus raising a zero_divide error?) if so do
case Number_Of_Calls when 0 then 0 else ((Number_of_answered/Number_Of_Calls)*100) as answer_percent
As far as I understood you from your comment you want a rate of answered calls over a period of time, including days when 100% calls were unanswered.
I guess the simpliest approach would be
select sum(number_of_answered) / sum (number_of_calls)
from table
where date between interval_start and interval_end
in this case.

IIF in With Member comparing dates

I am very new to MDX and have a basic question. I would like a calculated measure which returns one value for dates less than a specified date, and another value if greater than a specified date. I have attempted:
with member [measures].[tempmeasure] as
IIF
(
[Date].[Date].CurrentMember < [Date].[Date].&[20100501]
, 1
, 2
)
select
[Date].[Date].Members
*
[measures].[tempmeasure] on columns
from [MyCube]
And this does not seem to work. That is using MS SSAS 2008.
Any ideas what I could be doing wrong?
With:
IIF([Date].[Date].CurrentMember < [Date].[Date].&[20100501], 1, 2)
you're comparing two tuple values and not the date members themselves.
You can have a look here for a tutorial on tuples, sets, etc...
As you're using AS, I think you can use the DataDiff function to compute the number of days between your two dates:
DateDiff("d", [Date].[Date].CurrentMember.MemberValue, [Date].[Date].&[20100501].MemberValue )
Otherwise, you may have some member properties available for that purpose:
IIF([Date].[Date].CurrentMember.Properties( 'prop-name', TYPED ) < [Date].[Date].&[20100501].Properties( 'prop-name', TYPED ) , 1, 2)
Cheers.
Please use below expression
IIF
(
[Date].[Date].Currentmember.MemberValue <
[Date].[Date].&[20100501].MemberValue
, 1
, 2
)
I have tested it is working as expected.....
Please let me know if you have any questions
IIF expects a logical expression which returns a boolean value. I think in your case
[Date].[Date].CurrentMember will return a dimension value, a set. Less than operator in this case will cause a syntax error.