GROUP BY日期范围

时间:2013-10-25 12:37:47

标签: mysql sql datetime select group-by

CREATE TABLE `connectionLog` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `serverTimeConnected` datetime NOT NULL,
  `serverTimeDisconnected` datetime  NOT NULL,
  PRIMARY KEY (`ID`)
);

使用此查询,我将获得serverTimeConnected在一小时内的所有ID。

SELECT  HOUR( `serverTimeConnected`) as STUNDE, 
    count(`ID`) as HITS 
FROM    `connectionLog` 
GROUP BY HOUR( `serverTimeConnected`)

但我需要serverTimeConnected和serverTimeDisconnected之间的所有ID。

ID  serverTimeConnected serverTimeDisconnected
1   10:00:00            10:10:00    
2   10:00:00            11:10:00    
3   10:00:00            12:10:00

我需要一个结果 - 比如

STUNDE  HITS
10,     3
11,     2
12,     1

3 个答案:

答案 0 :(得分:1)

更新:我找到了这个解决方案

 SELECT Stunden.ID, COUNT(Stunden.ID) as HITS FROM Stunden
INNER JOIN connectionLog cl 
  ON (
    (ADDTIME(DATE_FORMAT(cl.serverTimeConnected,'%Y-%m-%d 00:00:00'),CONCAT(Stunden.ID,":00:00")) 
      BETWEEN cl.serverTimeConnected AND cl.serverTimeDisconnected)
    OR
      (ADDTIME(DATE_FORMAT(cl.serverTimedisConnected,'%Y-%m-%d 00:00:00'),CONCAT(Stunden.ID,":00:00")) 
      BETWEEN cl.serverTimeConnected AND cl.serverTimeDisconnected)
     )

GROUP BY Stunden.ID

http://sqlfiddle.com/#!2/6f3b0/11(已更新)

表格Stunden是所有可用时段的列表。 当连接和断开之间的小时(看一天)时,一个简单的INNER JOIN获取我们搜索的匹配数。 然后Group by小时,我们匹配右HITS

答案 1 :(得分:0)

group_concat

怎么样?
SELECT  HOUR( `serverTimeConnected`) as STUNDE, 
        count(`ID`) as HITS,
        group_concat(id) as IDs
FROM    `connectionLog` 
GROUP BY HOUR( `serverTimeConnected`)

答案 2 :(得分:-1)