gemGreg
gemGreg

Reputation: 194

How to group by table with null values together

I have table with rows:

Id, Name, Age, Field1, Field2
-----------------------------
1, 'Person_1', 23, NULL, 5
2, 'Person_1', 23, 3, NULL
3, 'Person_2, 25, 7, NULL

I want to group it to have result like this:

'Person_1', 23, 3, 5
'Person_2, 25, 7, NULL

I tried to do subquery and select Field1 and Field2 but it always gets first row of single person for field1 and field2

Upvotes: 0

Views: 52

Answers (1)

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

Use GROUP BY:

SELECT Name, MAX(Age), MAX(Field1), MAX(Field2)
FROM mytable
GROUP BY Name

MAX aggregate function will return NULL if all, e.g. Field2, values are NULL, otherwise it will ignore NULLs and return the maximum value of the field.

Demo here

Upvotes: 1

Related Questions