感谢任何可以提供帮助的人。我正在使用MSSQL 2005
我有一个像这样的数据库
SegmentDT DateTime,
WhoCalled varchar(4)
我想要做的就是找到所有在5分钟之内接听电话的WhoCalled。
我该如何做到这一点?
答案 0 :(得分:1)
所以:
SELECT
WhoCalled, COUNT(DISTINCT SegmentDT)
FROM
MyTable a
INNER JOIN
MyTable b ON a.WhoCalled = b.WhoCalled
WHERE
ABS(DateDiff(second, a.SegmentDT, b.SegmentDT)) <= 300
另一种方法是使用窗口功能。这将比较相邻的行:
;WITH CTE AS
(
SELECT
WhoCalled,
ROW_NUMBER() OVER (ORDER BY SegmentDT) AS RowNum
FROM
MyTable
)
SELECT
WhoCalled, COUNT(*)
FROM
CTE a
INNER JOIN
CTE b ON a.WhoCalled = b.WhoCalled AND a.RowNum + 1 = b.RowNum
WHERE
DateDiff(second, a.SegmentDT, b.SegmentDT) <= 300
答案 1 :(得分:0)
SELECT WhoCalled, count(*)
FROM tbl a
INNER JOIN tbl b ON a.WhoCalled = b.WhoCalled
AND DateDiff(n, a.SegmentDT, b.SegmentDT) > 0
AND DateDiff(n, a.SegmentDT, b.SegmentDT) <= 5