MySQL GROUP BY and COUNT over Multiple Columns



我有一个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

但这会为每天的每个独特价值创建一个新的组。

实现这一点的一种方法是生成一个子查询,该子查询使用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

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

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;
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

相关内容

  • 没有找到相关文章

最新更新