I have the following structre
id val
1 ...
.
.
2 ...
.
.
3 null
3 null
3 null
4 ...
.
.
Basically each id has multiple no. of values. And an id has either all values as integers or all values as null
What I want is to perform an aggregate (like AVG) on val group by id. If that id has null values, I want to put 5 there.
#1
SELECT id, (CASE SUM(val) WHEN null THEN 5 ELSE AVG(val) END) AS ac FROM tt GROUP BY id
> executes ELSE even for id = 3
In CASE, there should be an aggregate function that when done on null values give null.
I checked SUM and MAX like
SELECT SUM(val) FROM tt WHERE id = 3
> null
and it gives null here but doesn’t work in main statement. I guess it is related to the type of equality and hence tried WHEN IS NULL
but its a syntax error.
Also, is there some more standard way of indicating group of values as all null rather than using SUM or MAX.
2
Answers
The exact problem with your
CASE
expression is that to check for null in MySQL we have to useIS NULL
rather than equality. So use this version:But we might as well just use
COALESCE()
to assign an average of 5 for thoseid
groups having all null values.Note that the
AVG()
function by default ignores nulls. Therefore, the expressionAVG(val)
would only be null if every record in anid
group were having null forval
.You can use
if
condition :check here : https://dbfiddle.uk/Uso9nNTM