如何在mysql中基于id组合

时间:2016-11-30 14:57:04

标签: mysql database

请帮助查找结果。如何编写查询以组合具有相同ID的行

 id   size   sizeorder  color  colororder
  1    M       1         null     null
  1    null    null      red       1
  2    s       1         null     null
  2    Null    null      green      2

输出应该是

 id   size   sizeorder  color  colororder
  1    M       1         red       1
  2    s       1         green      2

2 个答案:

答案 0 :(得分:2)

SELECT id,
       MAX(size) AS size,
       MAX(sizeorder) AS sizeorder,
       MAX(color) AS color,
       MAX(colororder) AS colororder
FROM yourTable
GROUP BY id

您尝试执行的汇总与数据透视查询中发生的情况类似。 "秘密酱"在上面的查询中,MySQL的MAX函数忽略NULL值。这意味着,在您的表格中,对于每个分组NULL,每个列中仅保留非id值。

答案 1 :(得分:0)

你必须加入你的表和用例何时获得非空的值:

select case when t1.size is null then t2.size else t1.size end as size, 
  case when t1.sizeorder is null then t2.sizeorder else t1.sizeorder end as sizeorder,
  case when t1.color is null then t2.color else t1.color end as color 
  case when t1.colororder is null then t2.colororder else t1.colororder end as colororder 

from <table> t1 join <table> t2 on t1.id = t2.id