T-SQL select sum of Two integer column - sql

I have two columns Val1 and Val2 as int in SQL Server 2008
When I select Tot = Val1+Val2 from Table, I get null as Tot
How do I get total of two int columns selected?
Many thanks.

It's likely that you have a null value in one of the columns. that will produce a null-valued result.
You can do the following, if you want null to represent 0.
SELECT Tot = ISNULL(Val1, 0) + ISNULL(Val2, 0)
FROM Table

Use select Tot = isnull(Val1, 0) + isnull(Val2, 0) from Table

Related

Where condition with integer values return same as ir were a string

These two queries in SparkSQL return the same value and I don't know why.
Treating the condition attribute as integer or string.
select count(*) from <my_table> where <my_column> = 100
union all
select count(*) from <my_table> where <my_column> = '100'
In Logical plan it cast string values to int values based on schema refer this to understand more - https://medium.com/datalex/sparks-logical-and-physical-plans-when-why-how-and-beyond-8cd1947b605a
where column = 0 ............................................and where column = '0'

IF equals or clause

I have a stored procedure that runs two separate queries and puts the data into two temporary tables. I then have an IF statement below that, depending on the outcome will display one of the two tables.
DECLARE #DATASET1 AS FLOAT
DECLARE #DATASET2 AS FLOAT
SET #DATASET1 = (SELECT SUM(PREM) FROM #Prem1)
SET #DATASET2 = (SELECT SUM(PREM) FROM #Prem2)
IF (#DATASET1 = 0)
BEGIN
SELECT DATE,
SUM(PREM) AS PREM
FROM #DATASET2
GROUP BY YEAR, MONTH, DATE
ORDER BY YEAR, MONTH
END
IF (#DATASET2 = 0)
BEGIN
SELECT DATE,
SUM(PREM) AS PREM
FROM #DATASET1
GROUP BY YEAR, MONTH, DATE
ORDER BY YEAR, MONTH
END
This was working well until I hit some output on dataset1 that didn't produce 0 but just produced no data at all.
So I was wondering if it is possible to update this part of the query to almost say:
IF (#DATASET1 = 0 or '')
I have tried something like that but doesn't seem to work, hence my question.
Your scalar aggregate query (SELECT SUM(PREM) FROM #Prem1) will return a NULL value if there is no record in the table or of column PREM contains only NULL values.
You can handle NULL with IS NULL, like so:
IF (#DATASET1 IS NULL OR #DATASET1 = 0)
You can also use COALESCE():
IF (COALESCE(#DATASET1, 0) = 0)
You can achieve it by using ISNULL()
IF (ISNULL(#DATASET1, 0) = 0)
Syntax: ISNULL(expression, value)
Parameter Description
expression Required. The expression to test whether is NULL
value Required. The value to return if expression is NULL

Why Sum in database query giving NULL

Suppose I have a table named "Expense" and it has some month-wise expense which may contain some "NULL", now I want to check the yearly expenses in total with this below query:-
Select Sum(January) + Sum (February) ..... (I skipped the rest 10 months)
from Expense
This gives result as "NULL"
How can I avoid this situation? I think there are more convenient way to check the yearly sum
All arithmetic or logical operations involving NULL yield NULL. For example:
SELECT 1 + NULL -- NULL
You must convert NULL to zeros before you can + them:
SELECT
COALESCE(SUM(January), 0) +
COALESCE(SUM(February) , 0) +
...
It is also possible to add the columns first and then calculate the sum:
SELECT SUM(
COALESCE(January, 0) +
COALESCE(February, 0) +
)
Be advised that (i) SUM skips NULL values (ii) returns NULL instead of 0 if all values are NULL:
SELECT SUM(a) FROM (VALUES
(1),
(2),
(NULL)
) AS v(a) -- returns 3 instead of NULL
It will return NULL if all values encountered were NULL:
SELECT SUM(a) FROM (VALUES
(CAST(NULL AS INT)),
(NULL),
(NULL)
) AS v(a) -- returns NULL instead of 0
use coalesce function to convert null to 0 then use sum
Select Sum(coalesce(January,0)) + Sum (coalesce(February,0)) ..... (I skipped the rest 10 months)
from Expense
Just use coalesce [ with 0 as the second argument ] to replace nulls for all month columns, otherwise you can not get true results from aggregation of numeric values :
select sum(coalesce(January,0)+coalesce(February,0) ... )
from Expense
That because you have NULL values, you can use Case, Coalesce or IIF:
Select SUM(IIF(Col IS NULL, 0, Col))
Select SUM(CASE WHEN Col IS NULL THEN 0 ELSE Col END)
Select COALESCE(Sum(Col), 0)
Any arithmetic function will return null if there is at least one null value in the given column. That's why you should use functions like coalesce or isNull (MSSQL), NVL (Oracle).
You can use ISNULL(SUM(January),0).
Because null + value is always null and in your sample some months sums are null, you can avoid this by adding ISNULL
Select isnull(Sum(January),0) +
isnull(Sum(February),0)
--..... (I skipped the rest 10 months)
from Expense
Alternatively you can use below way:
Select Sum(
isnull(January,0) +
isnull(February,0)
)
--..... (I skipped the rest 10 months)
from Expense

Query returning null values but there is no error

I am picking values from a column TRANSAMT from the table GLPJD. The value can be negative in the table but when it's negative, I have to make it positive and when its positive, I leave it like that. The result being returned in NULL, what is left in the query. It is a subquery
declare #FY int
set #FY = 2016
SELECT
DbName, District,
(SELECT
CASE
WHEN (TRANSAMT < 0)
THEN ISNULL(SUM(TRANSAMT) * -1, 0)
ELSE ISNULL(SUM(TRANSAMT), 0)
END
FROM
GLPJD
LEFT JOIN
GLAMF ON GLPJD.ACCTID = GLAMF.ACCTID
WHERE
GLPJD.AUDTORG = D.DbName
AND GLPJD.ACCTID = 110002
AND GLPJD.FISCALYR < #FY
GROUP BY
TRANSAMT) AS TRANSAMT
FROM
Districts D
Results of the query:
Your error comes probably from the fact that performing a SUM while having NULL values returns a NULL result. So you should use the ISNULL part inside SUM, and not the other way around.
Also you may consider using the function ABS, so you could get rid of the CASE part. My approach would be changing this part from your current code:
SELECT
CASE
WHEN (TRANSAMT < 0)
THEN ISNULL(SUM(TRANSAMT) * -1, 0)
ELSE ISNULL(SUM(TRANSAMT), 0)
END
To just:
SELECT SUM(ABS(ISNULL(TRANSAMT, 0)))
sum function omits null values
look:
http://sqlfiddle.com/#!4/0a806/1

SQL adding numbers while handling nulls

I have this statement here:
SELECT sum(table1.foo + table1.bar) AS Sum
FROM table1
GROUP BY Fname;
When I try to add the numbers from foo and bar if one value from foo or bar is null it throws the numbers and gives me a different count sum
foo | bar
6 4
5 null
9 1
2 1
3 null
I want it to add all the numbers giving me a total of 31
but in this case it gives me a total of 23
Would love some help! Thanks!
Use coalesce():
SELECT sum(coalesce(table1.foo, 0) + coalesce(table1.bar, 0)) AS Sum
FROM table1
GROUP BY Fname;
If you want the total, total on one row, remove the group by:
SELECT sum(coalesce(table1.foo, 0) + coalesce(table1.bar, 0)) AS Sum
FROM table1;
Any Number + NULL = NULL. You want to indicate to the engine that when it sees a NULL, it should treat that NULL value as 0.
SELECT sum(ISNULL(table1.foo, 0) + ISNULL(table1.bar,0)) AS Sum
FROM table1
GROUP BY Fname;
I believe you'll need to have SQL replace nulls with a zero using "ISNULL".
Try:
SELECT sum(ISNULL(fix_bat_sum.foo, 0) + ISNULL(fix_bat_sum.bar, 0) ) AS Sum