2015-07-04 161 views
4

我有一個MySQL表如下:MySQL的GROUP BY和COUNT在多列

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

我將如何GROUP BY和計算所有的日子,讓每個傳輸超過一週的總模式。例如:

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

我已經嘗試使用:

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

但是,這創造了在每一天的每個唯一值的新組。要做到這一點

回答

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

如果你有模式的一個單獨的表,你也可以這樣做:

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;