根据mysql中的特定列切换行和列

时间:2017-02-22 05:44:55

标签: mysql ruby

我在MySQL中有一个表格,如下所示

**row      name     value**
 1         name1    value1
 1         name2    value2
 1         name3    value3
 2         name1    value4
 2         name2    value5
 2         name4    value6
 3         name1    value7
 3         name2    value8
 3         name3    value9

我想以下列格式返回数据。

**row      name1     name2     name3      name4**
  1        value1    value2    value3     nil
  2        value4    value5    nil        value6
  3        value7    value8    value9     nil

或者我想要一个看起来像的json:

{
 {
  name1:value1,
  name2:value2,
  name3:value3,
 },
 {
  name1:value4,
  name2:value5,
  name4:value6,
 },
 {
  name1:value7,
  name2:value8,
  name3:value9,
 },
}

查询可以是什么? 还有其他方法可以在ruby中实现吗?

2 个答案:

答案 0 :(得分:2)

对于第一个选项,您可以尝试以下数据透视查询:

SELECT row,
       MAX(CASE WHEN name ='name1' THEN value END) AS name1,
       MAX(CASE WHEN name ='name2' THEN value END) AS name2,
       MAX(CASE WHEN name ='name3' THEN value END) AS name3,
       MAX(CASE WHEN name ='name4' THEN value END) AS name4
FROM yourTable
GROUP BY row

答案 1 :(得分:0)

select row,
       max(case when name ='name1' then value end)  as name1,
       max(case when name ='name2' then value end)  as name2,
       max(case when name ='name3' then value end)  as name3,
       max(case when name ='name4' then value end ) as name4
from table_name 
group by row