将mysql中的列分成多列

时间:2017-02-05 15:21:10

标签: mysql sql nested-query

我是mysql的新手。在这里,我尝试在mysql中进行查询,根据排序顺序将列col1划分为4个不同的列(col2),如下所示。到目前为止,我已经写了这样的查询:

select if(category = 'first',name ,NULL) as first,
if(category = 'second',name,NULL) as second,
if(category = 'third',name,NULL) as third,
if(category = 'fourth',name,NULL) as fourth
from 'table';

这段代码给了我四列但我现在卡住了,因为我无法进一步过滤这个。

给出表:

name     category
John     first
Sunil    third
Jenny    third
Ashley   fourth
Meera    second
Abhay    first

必填答案:

col1    col2    col3    col4
Abhay   Meera   Jenny   Ashley
John    NULL    Sunil   NULL

请注意,答案中的所有列都已排序。

  

编辑:我猜这个问题并不清楚最终答案的格式。谢谢@philipxy指出。应该在最少的行数(在我的情况下是2)调整最终答案。所有列都应具有相同的行数,如果某些列的值较小,则该行在相应的列中将具有NULL值,例如上面的col2col 4。最后所有列都应按排序顺序,其中NULL将在最后一个(如果有的话),例如,假设有一个名为Olly的条目category fourth那么它应该是出现在NULL之前和col4之后的Ashley之前。

2 个答案:

答案 0 :(得分:1)

这很棘手。您正在尝试垂直堆叠列表,而不是水平堆栈,这不是"正常" SQL操作。

您可以使用条件聚合执行您想要的操作。问题是没有什么可以汇总的。解决方案是引入变量列来计算聚合的序列号:

select max(case when category = 'first' then name end) as first,
       max(case when category = 'second' then name end) as second,
       max(case when category = 'third' then name end) as third,
       max(case when category = 'fourth' then name end) as fourth
from (select t.*,
             (@rn := if(@c = category, @rn + 1,
                        if(@c := category, 1, 1)
                       )
             ) as rn
      from `table` t cross join
           (select @c := '', @rn := 0) params
      order by category
     ) t
group by rn;

如果您希望每列中的特定顺序的值,请在category之后添加第二个排序键。

编辑:

我应该注意,如果您不需要多行,只需要多个值,您可以将它们连接在一起:

select group_concat(case when category = 'first' then name end) as firsts,
       group_concat(case when category = 'second' then name end) as seconds,
       group_concat(case when category = 'third' then name end) as thirds,
       group_concat(case when category = 'fourth' then name end) as fourths
from`table` t
group by rn;

答案 1 :(得分:0)

试试这个

select if(category = 'first',name ,NULL) as first,
if(category = 'second',name,NULL) as second,
if(category = 'third',name,NULL) as third,
if(category = 'fourth',name,NULL) as fourth
from table1 ORDER BY name;

<强>输出

|  first | second |  third | fourth |
|--------|--------|--------|--------|
|  Abhay | (null) | (null) | (null) |
| (null) | (null) | (null) | Ashley |
| (null) | (null) |  Jenny | (null) |
|   John | (null) | (null) | (null) |
| (null) |  Meera | (null) | (null) |
| (null) | (null) |  Sunil | (null) |