我有一个像这样的表(在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条记录返回,但我不确定...... 你能帮忙吗?
答案 0 :(得分:0)
您可以使用id
和group 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