MySQL GROUP BY和COUNT over Multiple Columns

时间:2015-07-04 08:55:51

标签: mysql sql select count

我有一个MySQL表如下:

+----+-------+-------+-------+-------+-------+
| ID |  MON  |  TUE  |  WED  |  THU  |  FRI  |
+----+-------+-------+-------+-------+-------+
|  0 |  Bike |  Bike |  Walk |  Bike |  Car  |
|  1 |  Car  |  Car  |  Car  |  Bus  |  Car  |
|  2 |  Bus  | Train |  Bus  |  Bus  | Train |
|  3 |  Car  |  Car  |  Car  |  Walk |  Car  |
+----+-------+-------+-------+-------+-------+

我如何分组并统计所有日子,以获得一周内每次运输的总体模式。例如:

+--------+-------+
|  MODE  | COUNT |
+--------+-------+
|  Bike  |   3   |
|   Bus  |   4   |
|   Car  |   9   |
|  Train |   2   |
|  Walk  |   2   |
+--------+-------+

我尝试过使用:

SELECT COUNT(*), Mon 
FROM transport 
GROUP BY Mon, Tue, Wed, Thu, Fri

但是这会在每天为每个唯一值创建一个新组。

2 个答案:

答案 0 :(得分:4)

执行此操作的一种方法是生成一个子查询,使用union all运算符在一列中选择传输模式,然后计算出现次数:

SELECT   mode, COUNT(*)
FROM     (SELECT mon AS mode FROM transport UNION ALL
          SELECT tue AS mode FROM transport UNION ALL
          SELECT wed AS mode FROM transport UNION ALL
          SELECT thu AS mode FROM transport UNION ALL
          SELECT fri AS mode FROM transport) t
GROUP BY mode

答案 1 :(得分:1)

如果你有一个单独的模式表,你也可以这样做:

select m.mode, count(*)
from modes m join
     transport t
     on m.mode in (t.mon, t.tue, t.wed, t.thu, t.fri)
group by m.mode;