1

我对mysql完全陌生。在这里,我尝试进行一个查询,其中根据其类别()按如下所示的排序顺序mysql将一列分为 4 个不同的列。到目前为止,我已经写了一个这样的查询:col1col2

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最后一个(如果有的话)中,例如假设有一个名为的条目Ollycategory fourth那么它应该出现在NULLin之前col4和之后Ashley

4

1 回答 1

2

这很棘手。您正在尝试垂直堆叠列表,而不是水平堆叠列表,这不是“正常”的 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;
于 2017-02-05T15:29:24.787 回答