2

我有一张看起来像这样的桌子

id | startTime           | endTime
1  | 2012-11-07 12:33:23 | 2012-11-07 12:44:44
3  | 2012-11-07 12:45:55 | 2012-11-07 12:48:43
9  | 2012-11-07 12:47:23 | 2012-11-07 13:00:00
13 | 2012-11-08 12:32:22 | 2012-11-08 13:00:00

如何编写返回我的查询

id | CountNumIDsBeforeThisIDOnSameDay | CountNumIDsThatEndedBeforeThisIDOnSameDay
1  | 0                                | 0
3  | 1                                | 1
9  | 2                                | 1
13 | 0                                | 0

其他假设

id 可能不在流水号中

我不知道如何用简单的方式表达我的想法。但基本上,我知道如果我可以在子查询中引用当前行 ID,我可以轻松获得计数。我也在考虑使用LEFT OUTER JOINS,但我不确定我自己是否使事情复杂化。

4

1 回答 1

1

SQLFiddle 演示

select id,
(select count(*) from T 
    where DATE(startTime)=DATE(T1.startTime)
          AND 
          StartTime<T1.StartTime  
) as 
CountNumIDsBeforeThisIDOnSameDay,

(select count(*) from T 
    where DATE(startTime)=DATE(T1.startTime)
          AND 
          EndTime<T1.StartTime  
) as 
CountNumIDsThatEndedBeforeThisIDOnSameDay


from T as T1
Order by StartTime
于 2013-11-07T07:58:51.113 回答