我有这张桌子:
| name | gender | date |
------------------------------------
| Foo | male | 2013-09-16 10:23 |
| Name | male | 2013-09-16 09:10 |
| Red | male | 2013-09-15 09:10 |
| Bar | female | 2013-09-15 10:10 |
etc...
我需要按gender
过滤每周的每天访问次数。
所以我应该得到,如果算上男性:
1: 2 visits
2: 0 visits
3: 0 visits
4: 0 visits
5: 0 visits
6: 0 visits
7: 1 visit
查询应为:
SELECT FROM table
WHERE gender = 'male'
GROUP BY DAYOFWEEK
我的查询不起作用所以我在这里询问是否有人知道如何使其有效...
答案 0 :(得分:2)
尝试
SELECT dayofweek(date) dayofweek, gender, count(*) count
FROM table
GROUP BY DAYOFWEEK(date), gender
编辑:
如果你想让星期一为1,星期日为7,你也可以
SELECT (dayofweek(date)+5)%7+1 dayofweek, gender, count(*) count
FROM table
GROUP BY (dayofweek(date)+5)%7+1, gender
如果你想避免if
构造......
答案 1 :(得分:1)
使用WEEKDAY()代替,它从星期一开始。
SELECT WEEKDAY(date) weekday, gender, count(*) count
FROM table
GROUP BY WEEKDAY(date), gender
如果您需要从索引1开始,请使用或WEEKDAY()+ 1。
SELECT (WEEKDAY(date)+1) weekday, gender, count(*) count
FROM table
GROUP BY WEEKDAY(date), gender