MySQL - 将多行包装成一行

时间:2014-04-18 12:33:41

标签: mysql

我在MySQL中有这个数据集,其中记录需要折叠成一行,但是,要回滚的列数会有所不同。这是一个例子:

Id     Name                  Pre/Post    Attempt     Other Data
--     --------              --------    -------     ----------
1      James Owens              Pre         1          blah
1      James Owens              Post        1          blah
1      James Owens              Post        2          blah

2      Derek Williams           Post        1          blah
2      Derek Williams           Post        2          blah
2      Derek Williams           Post        3          blah

3      Sean Parker              Pre         1          blah

4      Miles Taylor             Pre         1          blah
4      Miles Taylor             Post        1          blah
4      Miles Taylor             Post        2          blah
4      Miles Taylor             Post        3          blah
4      Miles Taylor             Post        4          blah

尝试次数最多的是4.我希望数据以这种方式结束(或者接近这一点):

Id     Name                     Pre         Post      Post      Post      Post      Other Data
--     -------------            ---         ----      ----      ----      ----      ----------
1      James Owens               1           1         2                            blah
2      Derek Williams                        1         2         3                  blah
3      Sean Parker               1                                                  blah
4      Miles Taylor              1           1         2         3         4        blah

我知道你会问"你有什么尝试?" - 好吧,我没有尝试任何东西,因为我不知道从哪里开始。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

正如Ryan在评论中提到的,你可以只有两列来存储尝试前后的计数。你可以通过以下方式实现这一目标:

select distinct(tbl.id), name, pre_count.count, post_count.count, other_data
from `tbl` left join (select id, count(*) as count
                      from `tbl` where pre_post = 'pre' group by id) as pre_count
                      on tbl.id = pre_count.id
           left join (select id, count(*) as count
                      from `tbl` where pre_post = 'post' group by id) as post_count
                      on tbl.id = post_count.id