在一个表中按列分组

时间:2015-08-05 17:40:28

标签: mysql sql

我有这样的表:

Year    Month   Item  val1 val2 val3
2011        1   A       86      
2011        1   B       17      
2012        2   B       10      
2012        2   C       1       
2013        3   A       82      
2013        3   B       89      
2011        1   A           59  
2011        1   B           75  
2012        2   B           26  
2012        2   C           77  
2013        3   A           62  
2013        3   B           78  
2011        1   A               70
2011        1   B               17
2012        2   B               15
2012        2   C               20
2013        3   A               62
2013        3   B               43

我希望看起来像这样:

Year    Month Item  val1 val2 val3
2011        1   A     86    59  70
2011        1   B     17    75  17
2012        2   B     10    26  15
2012        2   C     1     77  20
2013        3   A     82    62  62
2013        3   B     89    78  43

我尝试这样的查询:

select year,month,item,val1,val2,val3 from table
group by year,month,item

但它不起作用 有人可以帮帮我吗?感谢

1 个答案:

答案 0 :(得分:1)

尝试类似于某些聚合函数的内容:

select year,month,item,
    MAX(COALESCE(val1,0)) as val1,MAX(COALESCE(val2,0)) as val2,MAX(COALESCE(val3,0)) as val3 from table
group by year,month,item