简体   繁体   中英

Count occurrences for each day of week

I have this table:

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

I need to get the number of visits of each day of week filtering by gender .

So I should get, if I count the males:

1: 2 visits
2: 0 visits
3: 0 visits
4: 0 visits
5: 0 visits
6: 0 visits
7: 1 visit

The query should be:

SELECT FROM table
WHERE gender = 'male'
GROUP BY DAYOFWEEK

My query doesn't work so I'm asking here if someone know how to make it works...

Try

SELECT dayofweek(date) dayofweek, gender, count(*) count
FROM table
GROUP BY DAYOFWEEK(date), gender

Edit:

If you want to have Monday as 1 and Sunday as 7 you can also do

SELECT (dayofweek(date)+5)%7+1 dayofweek, gender, count(*) count
FROM table
GROUP BY (dayofweek(date)+5)%7+1, gender

if you want to avoid the if construct ...

Use WEEKDAY() instead, it begins on Monday.

SELECT WEEKDAY(date) weekday, gender, count(*) count
FROM table
GROUP BY WEEKDAY(date), gender

If you need to start at index 1, use or WEEKDAY() + 1.

SELECT (WEEKDAY(date)+1) weekday, gender, count(*) count
FROM table
GROUP BY WEEKDAY(date), gender

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM