如何按行为控制组?

时间:2013-10-25 07:03:12

标签: mysql group-by

我想获得一个活动的所有舞台,课程,状态。问题是某些阶段有几行:

mysql> select stage,class,status from results where event=3009 and person=81451;
+-------+-------+-----------+
| stage | class | status    |
+-------+-------+-----------+
|  3210 | 52800 | OK        |
|  3209 | 52800 | Cancelled |
|  3208 | 52800 | OK        |
|  3209 | 52798 | OK        |
+-------+-------+-----------+
4 rows in set (0,01 sec)

每个阶段我只想要一行。所以我的想法是使用group by:

mysql> select stage,class,status from results where event=3009 and person=81451 group by stage;
+-------+-------+-----------+
| stage | class | status    |
+-------+-------+-----------+
|  3208 | 52800 | OK        |
|  3209 | 52800 | Cancelled |
|  3210 | 52800 | OK        |
+-------+-------+-----------+
3 rows in set (0,00 sec)

但是在多行的情况下,我希望选择status = OK行。我怎么能这样做?

我想要最终得到的结果是:

+-------+-------+-----------+
| stage | class | status    |
+-------+-------+-----------+
|  3208 | 52800 | OK        |
|  3209 | 52798 | OK        |
|  3210 | 52800 | OK        |
+-------+-------+-----------+

1 个答案:

答案 0 :(得分:2)

由于OK大于CANCELLED,您可以使用MAX()

SELECT  a.*
FROM    results a
        INNER JOIN
        (
            SELECT  stage, MAX(status) status
            FROM    result
            WHERE   event = 3009 
                    AND person = 81451
            GROUP   BY stage
        ) b ON  a.stage = b.stage AND
                a.status = b.status