如何将MySQL行转换为5列
我是MySQL新手。我有一个数据表,我想把它转换成5行 从如何将MySQL行转换为5列,mysql,sql,string,pivot,window-functions,Mysql,Sql,String,Pivot,Window Functions,我是MySQL新手。我有一个数据表,我想把它转换成5行 从选择tbl\U文件中的文件。我有 +--------+ | File | +--------+ | B.jpg | +--------+ | X.jpg | +--------+ | H.png | +--------+ | C.png | +--------+ | A.gif | +--------+ | G.pdf | +--------+ | Y.docx | +--------+ | U.jpeg
选择tbl\U文件中的文件
。我有
+--------+
| File |
+--------+
| B.jpg |
+--------+
| X.jpg |
+--------+
| H.png |
+--------+
| C.png |
+--------+
| A.gif |
+--------+
| G.pdf |
+--------+
| Y.docx |
+--------+
| U.jpeg |
+--------+
当行旋转到5列时,我需要这样做
+-------+--------+--------+-------+-------+
| A | B | C | D | E |
+-------+--------+--------+-------+-------+
| B.jpg | X.jpg | H.png | C.png | A.gif |
+-------+--------+--------+-------+-------+
| G.pdf | Y.docx | U.jpeg | | |
+-------+--------+--------+-------+-------+
当第一行填充到其限制值5时,下一行继续填充
这就是我尝试过的:
按id从tbl_文件组中选择组_CONCAT(文件)代码>
我没有得到我想要的
非常感谢。有点难看。。。但这是可能的。您可以使用窗口函数,但您需要一个列来定义行的顺序,我假设id
select
max(case when rn % 5 = 0 then file end) as filea,
max(case when rn % 5 = 1 then file end) as fileb,
max(case when rn % 5 = 2 then file end) as filec,
max(case when rn % 5 = 3 then file end) as filed,
max(case when rn % 5 = 4 then file end) as filee
from (
select t.*, row_number() over(order by id) - 1 rn
from mytable t
) t
group by floor(rn / 5)
:
filea | fileb | filec | filed | filee
:---- | :----- | :----- | :---- | :----
B.jpg | X.jpg | H.png | C.png | A.gif
G.pdf | Y.docx | U.jpeg | null | null
文件A |文件B |文件C |文件|文件E
:---- | :----- | :----- | :---- | :----
B.jpg | X.jpg | H.png | C.png | A.gif
G.pdf | Y.docx | U.jpeg | null | null
只需处理应用程序中的显示逻辑即可code@strawberry我的应用程序代码中已经有很多循环。加上这个会使速度变慢。由于DB更快,我考虑直接运行它并返回一个表。