SQL Replacing NULL with 0 in a query - sql

I'm trying to replace a Null value with a 0 and then do a calculation on this field, but not able to make it work. In all 4 of the examples below I'm still getting a Null value.
Any suggestions with how to write this?
Here's what I've tried:
select
ISNULL(posamt, 0) as total1,
coalesce (posamt, 0) as total2,
case when PosAmt = 0 then '0' else CONVERT(varchar(11), isnull(posamt, 0))end as total3,
CONVERT(varchar(11),isnull(posamt,0)) as total4
from mytable

I believe you need to have the ISNULL(posamt,0) in the CASE WHEN statements. It will never be equal to 0 when posamt is NULL.

Related

way to have query with case statement

I have table called Numbers in that column I have values from 0 - 10 but I like to keep value of 1-10 only change record of 0 too null
Case numbers
when 0
then ''
but I found this has changed all values and not values that have 0 is there way I can say else leave value as is?
Do you want this?
update t
set number = null
where number = 0;
Or as a select:
select t.*,
(case when number <> 0 then number end)
from t;
SELECT CASE WHEN [column] = 0 THEN NULL ELSE [column] END AS [SomeName]
FROM Numbers

Case Statement embedded in NVL

I am trying to setup the below logic in as a divisor. I need to use NVL() to avoid the divide by zero error. I need to get a distinct count of the case statement.
Here is what I have:
(NVL(COUNT(DISTINCT
CASE WHEN ({field1} = 'a' OR {field1} = 'b' OR
{field1} = 'c' OR {field1} = 'd') AND
({field2} = 'a' OR {field2} = 'b') AND
({field3} > TO_DATE('01-JAN-2017', 'DD-MON-YYYY'))
THEN 1 END), 1))
There is something wrong with my syntax but cannot figure it out.
Any help would be appreciated. Thank you!
I changed lots of ORs to simpler IN
COUNT(DISTINCT
CASE
WHEN field1 IN ('a','b','c','d')
AND field2 IN ('a','b')
AND field3 > TO_DATE('01-JAN-2017', 'DD-MON-YYYY')
THEN 1
END)
COUNT(DISTINCT ...) doesn't return null, so removed redundant NVL
Now, the above will result is either 0 or 1.
You probably want this without distinct:
COUNT(
CASE
WHEN field1 IN ('a','b','c','d')
AND field2 IN ('a','b')
AND field3 > TO_DATE('01-JAN-2017', 'DD-MON-YYYY')
THEN 1
END)
Since, it is a divisor, it can't be 0, so you'll have to place safeguard for that. One sensible output in case the divisor is 0 is null. One way to achieve that is:
case when (expression) <> 0 then dividend/(expression) end

Replacing NULL with 0 in a SQL server query

I have developed a query, and in the results for the first three columns I get NULL. How can I replace it with 0?
Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
When you want to replace a possibly null column with something else, use IsNull.
SELECT ISNULL(myColumn, 0 ) FROM myTable
This will put a 0 in myColumn if it is null in the first place.
You can use both of these methods but there are differences:
SELECT ISNULL(col1, 0 ) FROM table1
SELECT COALESCE(col1, 0 ) FROM table1
Comparing COALESCE() and ISNULL():
The ISNULL function and the COALESCE expression have a similar
purpose but can behave differently.
Because ISNULL is a function, it is evaluated only once. As
described above, the input values for the COALESCE expression can be
evaluated multiple times.
Data type determination of the resulting expression is different.
ISNULL uses the data type of the first parameter, COALESCE follows
the CASE expression rules and returns the data type of value with
the highest precedence.
The NULLability of the result expression is different for ISNULL and
COALESCE. The ISNULL return value is always considered NOT NULLable
(assuming the return value is a non-nullable one) whereas COALESCE
with non-null parameters is considered to be NULL. So the
expressions ISNULL(NULL, 1) and COALESCE(NULL, 1) although
equivalent have different nullability values. This makes a
difference if you are using these expressions in computed columns,
creating key constraints or making the return value of a scalar UDF
deterministic so that it can be indexed as shown in the following
example.
-- This statement fails because the PRIMARY KEY cannot accept NULL values
-- and the nullability of the COALESCE expression for col2
-- evaluates to NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0) PRIMARY KEY,
col3 AS ISNULL(col1, 0)
);
-- This statement succeeds because the nullability of the
-- ISNULL function evaluates AS NOT NULL.
CREATE TABLE #Demo
(
col1 integer NULL,
col2 AS COALESCE(col1, 0),
col3 AS ISNULL(col1, 0) PRIMARY KEY
);
Validations for ISNULL and COALESCE are also different. For example,
a NULL value for ISNULL is converted to int whereas for COALESCE,
you must provide a data type.
ISNULL takes only 2 parameters whereas COALESCE takes a variable
number of parameters.
if you need to know more here is the full document from msdn.
With coalesce:
coalesce(column_name,0)
Although, where summing when condition then 1, you could just as easily change sum to count - eg:
count(case when c.runstatus = 'Succeeded' then 1 end) as Succeeded,
(Count(null) returns 0, while sum(null) returns null.)
When you say the first three columns, do you mean your SUM columns? If so, add ELSE 0 to your CASE statements. The SUM of a NULL value is NULL.
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
SQL Fiddle Demo
A Simple way is
UPDATE tbl_name SET fild_name = value WHERE fild_name IS NULL
If you are using Presto, AWS Athena etc, there is no ISNULL() function. Instead, use:
SELECT COALESCE(myColumn, 0 ) FROM myTable
Wrap your column in this code.
ISNULL(Yourcolumn, 0)
Maybe check why you are getting nulls
Use COALESCE, which returns the first not-null value e.g.
SELECT COALESCE(sum(case when c.runstatus = 'Succeeded' then 1 end), 0) as Succeeded
Will set Succeeded as 0 if it is returned as NULL.
Add an else to your case statements so that they default to zero if the test condition is not found. At the moment if the test condition isn't found NULL is being passed to the SUM() function.
Select c.rundate,
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
count(*) as Totalrun from
( Select a.name,case when b.run_status=0 Then 'Failed' when b.run_status=1 Then 'Succeeded'
when b.run_status=2 Then 'Retry' Else 'Cancelled' End as Runstatus,
---cast(run_date as datetime)
cast(substring(convert(varchar(8),run_date),1,4)+'/'+substring(convert(varchar(8),run_date),5,2)+'/' +substring(convert(varchar(8),run_date),7,2) as Datetime) as RunDate
from msdb.dbo.sysjobs as a(nolock) inner join msdb.dbo.sysjobhistory as b(nolock)
on a.job_id=b.job_id
where a.name='AI'
and b.step_id=0) as c
group by
c.rundate
sum(case when c.runstatus = 'Succeeded' then 1 else 0 end) as Succeeded,
sum(case when c.runstatus = 'Failed' then 1 else 0 end) as Failed,
sum(case when c.runstatus = 'Cancelled' then 1 else 0 end) as Cancelled,
the issue here is that without the else statement, you are bound to receive a Null when the run status isn't the stated status in the column description. Adding anything to Null will result in Null, and that is the issue with this query.
Good Luck!
by following previous answers I was losing my column name in SQL server db however following this syntax helped me to retain the ColumnName as well
ISNULL(MyColumnName, 0) MyColumnName
For regular SQL, ISNULL(item) can only take one parameter, and thus 90% of these solutions don't work.
I repurposed #Krishna Chavali's answer to make this:
(CASE WHEN (NOT ISNULL(column_name)) THEN column_name ELSE 0 END) AS ColumnName
This will return the value in column_name if it is not null, and 0 if it is null.
UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

How to count the rows which contains non zero values in sql

SELECT round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
FROM table;
Field dmd_1wk has so many zeros in it. How do I Count the non zero values?
It sounds like you just need to add a WHERE clause:
SELECT
round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
FROM table
WHERE dmd_1wk <> 0;
If you want the count of both non-zero and zero values, then you can use something like:
SELECT
round(COUNT(case when dmd_1wk <> 0 then dmd_1wk end),2) AS NBR_ITEMS_1WK_NonZero,
round(COUNT(case when dmd_1wk = 0 then dmd_1wk end),2) AS NBR_ITEMS_1WK_Zero
FROM table;
Method 1: Case Statement. This may be useful if you need to continue to process all rows (which a where clause would prevent).
SELECT count(case when dmd_1wk = 0 then 0 else 1 end) as NonZeroCount FROM MyTable
Method 2: Where Clause.
SELECT
count(1) as NonZeroCount
FROM
MyTable
WHERE
dmd_1wk <> 0
I'd like to offer another solution using NULLIF since COUNT won't count NULL values:
SELECT round(COUNT(NULLIF(dmd_1wk,0)),2) AS NBR_ITEMS_1WK
FROM table;
And here is the Fiddle.
Good luck.
Methinks bluefeets answer is probably what you are really looking for, as it sounds like you just want to count non-zeros; but this will get you a count of zero and non-zero items if that's not the case:
SELECT
ROUND(SUM(CASE NVL(dmd_1wk, 0) = 0 THEN 1 ELSE 0 END), 2) AS "Zeros",
ROUND(SUM(CASE NVL(dmd_1wk, 0) != 0 THEN 1 ELSE 0 END), 2) AS "NonZeros"
FROM table
Although there is no point in rounding a whole number, I've included your original ROUNDs as I'm guessing you're using it for formatting, but you might want to use:
TO_CHAR(SUM(...), '999.00')
as that's the intended function for formatting numbers.
You can filter them.
SELECT round(COUNT(dmd_1wk),2) AS NBR_ITEMS_1WK
FROM table
WHERE dmd_1wk <> 0;

SQL Query - Return Text based on numeric value

I am trying to work out a query where the query will perform a count (total) on a specific column. If the count is greater than 0, I want to display YES and display NO if the returned count is zero.
So, if I a query as this:
SELECT COUNT(ProblemID)
FROM dbo.ProblemInfo
WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')
that will actually be a subquery, how do I get the subquery to display "YES" when the returned count is greater than 0 and NO if the count is 0?
I appreciate any insight and help.
select isnull(
SELECT MAX('YES')
FROM dbo.ProblemInfo
WHERE ProblemID IN (100,101,309,305,205,600,500)
AND DEPID = '10866'),
'NO')
This is a trick to return either YES if there's at least one matching row, or null if not.
The wrapping isnull call then turns a null into a NO
Here's an alternate way of querying that.
IF EXISTS(
SELECT *
FROM dbo.ProblemInfo
WHERE (ProblemID IN (100,101,309,305,205,600,500))
AND (DEPID = '10866')
)
BEGIN
SELECT 'Yes'
END
ELSE
BEGIN
SELECT 'No'
END
What I like about this method is that, for enormous data-sets, it should be noticeably faster.
try
SELECT CASE
WHEN (SELECT COUNT(ProblemID) FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')) > 0
THEN 'YES'
ELSE 'NO' END
FROM YourTable
you can use case when.
SELECT
case
when COUNT(ProblemID) = 0 then 'NO'
else 'YES'
end
FROM dbo.ProblemInfo WHERE (ProblemID IN (100,101,309,305,205,600,500)) AND (DEPID = '10866')