giorgi bezhitashvili
giorgi bezhitashvili

Reputation: 76

Mysql how merge table data by column

GROUP BY does not work for this

I have this:

-----------------
name  col1  col2
-----------------
a     null  1
b     null  3
a     3     null
b     4     null

I need this result:

-----------------
name  col1  col2
-----------------
a     3     1
b     4     3

Upvotes: 1

Views: 26

Answers (2)

Matt
Matt

Reputation: 15071

Use MAX to eliminate the NULLs and then the GROUP BY function.

SELECT name, MAX(col1) AS col1, MAX(col2) AS col2
FROM yourtable
GROUP BY name

Output:

name col1 col2
a    3    1
b    4    3

Since you said GROUP BY does not work for this I am assuming it is part of a bigger query, maybe use sub queries to get your results?

SELECT t.name, 
      (SELECT MAX(ta.col1) FROM yourtable ta WHERE ta.name = t.name) AS col1,
      (SELECT MAX(tb.col2) FROM yourtable tb WHERE tb.name = t.name) AS col2
FROM yourtable t
GROUP BY t.name

Upvotes: 1

jarlh
jarlh

Reputation: 44766

I'd say GROUP BY is perfect here:

select name, max(col1) col1, max(col2) col2
from tablename
group by name

Upvotes: 0

Related Questions