MYSQL - 如何分组并获取非空值

时间:2016-02-18 14:45:44

标签: mysql sql

我有一个看起来像这样的表:

Name  | Color | Fruit | Animal
-----------------------------
Steve | Blue  | Null  | Null
Steve | Null  | Apple | Null
Steve | Null  | Null  | Sheep
John  | Red   | Apple | Null
John  | Null  | Null  | Cow

... ETC

我希望它浓缩成

Name  | Color | Fruit | Animal
------------------------------
Steve | Blue  | Apple | Sheep
John  | Red   | Apple | Cow

我试过的其他解决方案对Null来说并不是很好用。

1 个答案:

答案 0 :(得分:2)

您可以使用max和group by

SELECT t.name,
       max(t.color) as color,
       max(t.fruit) as fruit,
       max(t.animal) as animal)
FROM YourTable
GROUP BY t.name