每行多个记录查询

时间:2016-04-15 01:56:57

标签: mysql sql

我有一个像这样的表(在mysql中):

TABLE1

Id   Name   Age 
---------------
1    John   22
2    Mary   17
3    Peter  21
4    Agnes  34
5    Steve  14
6    Bart   26
7    Bob    32
8    Vince  18
...

我正在寻找的是一个SELECT语句,我可以连续获得4条记录。我的意思是,select语句的结果是:

Id1 Name1 Age1  Id2 Name2 Age2 Id3 Name3 Age3 Id4 Name4 Age4
-----------------------------------------------------------
1   John  22    2   Mary  17   3   Peter 21   4   Agnes 34
5   Steve 14    6   Bart  26   7   Bob   32   8   Vince 18
...

我想这会像一个支点...... 这可能吗?如果是,那我该怎么做呢? 我需要通过在一行上显示4条记录来填充报告,因此我希望能够从返回此确切结构的数据源中执行此操作。所以在第一个乐队/行上会有

rec1,rec2,rec3,rec4

然后在第二行:

rec5,rec6,rec7,rec8

等等。

我的第一个想法是合并4个查询,这些查询以1,2,3,4开头每5条记录返回,但我不确定...... 你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以使用idgroup by上的算术执行此操作:

select (case when id % 4 = 1 then id end) as id1,
       (case when id % 4 = 1 then name end) as name1,
       (case when id % 4 = 1 then age end) as age1,
       (case when id % 4 = 2 then id end) as id2,
       (case when id % 4 = 2 then name end) as name2,
       (case when id % 4 = 2 then age end) as age2,
       (case when id % 4 = 3 then id end) as id3,
       (case when id % 4 = 3 then name end) as name3,
       (case when id % 4 = 3 then age end) as age3,
       (case when id % 4 = 0 then id end) as id4,
       (case when id % 4 = 0 then name end) as name4,
       (case when id % 4 = 0 then age end) as age4
from t
group by floor((id - 1) / 4);

如果id没有间隙增加,那么你可以使用:

生成一个
from (select t.*, (@rn := @rn + 1) as seqnum
      from t cross join
           (select @rn := 0) params
      order by id
     ) t