2012-11-17 133 views
1

我想監視站點上不同類型的操作,我將使用登錄作爲示例。MySQL - 按時間戳範圍的組

user_logins table: 

user_id  name   when_logged 
-------  ----   ----------- 
smallint varchar(128) timestamp 

所以,看看誰登錄今日(多少次),每個用戶使用:

select name, count(name) from user_logins 
where when_logged between '2012-11-17 00:00:00' AND '2012-11-17 23:59:59' 
group by name; 

然而,我想要做的,在過去的14天,每一天seperately ...

是否可以在一個查詢中執行此操作,而不是通過更改日期執行14個查詢?

回答

1
select name, count(when_logged) 
from user_logins 
where when_logged >= curdate() - interval 14 day 
group by name, date(when_logged) 
+0

感謝 - 但是,這並不限制在過去14天因某種原因 –

+0

當然。修正了。 –

+0

完美,非常感謝! –

1
select date(when_logged) as datelogged, name, count(name) 
from user_logins 
where when_logged >= date_sub(current_timestamp, INTERVAL 14 day) 
group by name, date(when_logged); 
+0

非常感謝,非常感謝! –