我想获得DocID
的开始时间重叠计数在下面的例子中,9:00-9:15重叠在9:00-9:30 所以我希望DocID(111)的计数为2
=============================================================
EncID | Pid | DocID | Date | StartTime | EndTime|
=============================================================
1 | 11 | 111 | 25/3/2016 | 9:00 | 9:30 |
2 | 12 | 111 | 25/3/2016 | 9:00 | 9:15 |
3 | 13 | 111 | 26/3/2016 | 10:00 | 10:30 |
=============================================================
Expected Out put
==============
DocID | count|
==============
111 | 2 |
==============
答案 0 :(得分:1)
这样的事情应该有效并避免OR
。子查询应该有效运行。
SELECT
T1.DocID,
(
SELECT COUNT(*)
FROM [Table] T2
WHERE T1.DocID = T2.DocID
AND T1.[Date] = T2.[Date]
AND T1.StartTime <= T2.EndTime
AND T1.EndTime >= T2.StartTime
) AS [Count]
FROM [Table] T1
GROUP BY
T1.DocID
如果您还希望过滤以仅显示重叠的记录,则最好将子查询转换为连接(不是更高效,但绝对更容易过滤):< / p>
SELECT
T1.DocID,
COUNT(*) AS [Count]
FROM [Table] T1
INNER JOIN [Table] T2
ON T1.DocID = T2.DocID
AND T1.[Date] = T2.[Date]
AND T1.StartTime <= T2.EndTime
AND T1.EndTime >= T1.EndTime
GROUP BY
T1.DocID
HAVING
COUNT(*) > 1