MySQL如何在子集内进行分组

时间:2016-03-08 12:25:01

标签: mysql

创建表格foo(id,name,position)

insert into foo values (1, 'foo_a', 1);
insert into foo values (2, 'foo_b', 2);
insert into foo values (3, 'foo_c', 3);
insert into foo values (4, 'bar_b', 2);
insert into foo values (5, 'bar_a', 1);
insert into foo values (6, 'bar_c', 3);
insert into foo values (7, 'baz_a', 1);
insert into foo values (8, 'baz_b', 2);
insert into foo values (9, 'baz_c', 3);

我想要如下呈现上面的表,我应该写什么SQL。我无法有效地在子集内进行分组

baz_c, 3
baz_b, 2
baz_a, 1
bar_c, 3
bar_b, 2
bar_a, 1
foo_c, 3
foo_b, 2
foo_a, 1

1 个答案:

答案 0 :(得分:0)

试试这个:

SQL:

select 
    name, position, concat(name , ', ', position) output 
from 
    foo 
order 
    by CASE LEFT(name, 3) WHEN 'baz' THEN 1
                          WHEN 'bar' THEN 2
                          WHEN 'foo' THEN 3
       ELSE 0 END,
    position desc;

输出:

mysql> select
    ->     name, position, concat(name , ', ', position) output
    -> from
    ->     foo
    -> order
    ->     by CASE LEFT(name, 3) WHEN 'baz' THEN 1
    ->                           WHEN 'bar' THEN 2
    ->                           WHEN 'foo' THEN 3
    ->        ELSE 0 END,
    ->     position desc;
+-------+----------+----------+
| name  | position | output   |
+-------+----------+----------+
| baz_c |        3 | baz_c, 3 |
| baz_b |        2 | baz_b, 2 |
| baz_a |        1 | baz_a, 1 |
| bar_c |        3 | bar_c, 3 |
| bar_b |        2 | bar_b, 2 |
| bar_a |        1 | bar_a, 1 |
| foo_c |        3 | foo_c, 3 |
| foo_b |        2 | foo_b, 2 |
| foo_a |        1 | foo_a, 1 |
+-------+----------+----------+
9 rows in set (0.00 sec)