According to MS's knowledgebase,
Except for COUNT, aggregate functions ignore null values.
Does anyone know how I can get it to work correctly, that is, return a null if it attempts to aggregate with a null in the values?
Example:
SELECT SUM("col")
FROM (
SELECT NULL "col"
UNION
SELECT 1 "col"
) test
I would expect this query to return NULL
, not 1.
Mikael Eriksson
22.3k5 gold badges63 silver badges106 bronze badges
asked Feb 19, 2015 at 14:40
1 Answer 1
You can simulate this by applying a where clause to your query:
with test_data (col) as (
select null union all
select 1 union all
select 2
)
select sum(col)
from test_data
where not exists (select 1
from test_data
where col is null);
Edit
Andriy is right, this can also be written as:
with test_data (col) as (
select null union all
select 1 union all
select 2
)
select case
when count(*) = count(col) then sum(col)
else null
end
from test_data;
answered Feb 19, 2015 at 14:51
user1822user1822
-
2Seems a little overkill. You could just compare
COUNT(col)
andCOUNT(*)
.Andriy M– Andriy M2015年02月19日 14:55:05 +00:00Commented Feb 19, 2015 at 14:55 -
@AndriyM: good point, I added that as well. Thanksuser1822– user18222015年02月19日 15:02:35 +00:00Commented Feb 19, 2015 at 15:02
lang-sql
WHERE EXISTS (SELECT ... WHERE column iS NULL)