开发者

Concatenated range descriptions in MySQL

I have data in a table looking like this:

+---+----+
| a |  b |
+---+----+
| a |  1 |
| a |  2 |
| a |  4 |
| a |  5 |
| b |  1 |
| b |  3 |
| b |  5 |
| c |  5 |
| c |  4 |
| c |  3 |
| c |  2 |
| c |  1 |
+---+----+

I'd like to produce a SQL query which outputs开发者_运维百科 data like this:

+---+-----------+
| a |  1-2, 4-5 |
| b |  1,3,5    |
| c |  1-5      |
+---+-----------+

Is there a way to do this purely in SQL (specifically, MySQL 5.1?)

The closest I have got is select a, concat(min(b), "-", max(b)) from test group by a;, but this doesn't take into account gaps in the range.


Use:

     SELECT a, GROUP_CONCAT(x.island)
         FROM (SELECT y.a,
                               CASE
                                  WHEN MIN(y.b) = MAX(y.b) THEN
                                    CAST(MIN(y.b) AS VARCHAR(10))
                                  ELSE
                                    CONCAT(MIN(y.b), '-', MAX(y.b))
                               END AS island
                      FROM (SELECT t.a, t.b,
                                            CASE
                                                WHEN @prev_b = t.b -1 THEN
                                                    @group_rank
                                                ELSE
                                                  @group_rank := @group_rank + 1
                                            END AS blah,
                                            @prev_b := t.b
                                  FROM TABLE t
                                  JOIN (SELECT @group_rank := 1, @prev_b := 0) r
                           ORDER BY t.a, t.b) y
               GROUP BY y.a, y.blah) x  
GROUP BY a

The idea is if you assign a value to group sequencial values, then you can use MIN/MAX to get the appropriate vlalues. IE:

a  |  b | blah
---------------
a  |  1 | 1
a  |  2 | 1
a  |  4 | 2
a  |  5 | 2


I also found Martin Smith's answer to another question helpful:

printing restaurant opening hours from a database table in human readable format using php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜