我使用的查询是:
SELECT
a.What_Tech,
a.callid FirstCallid,
b.Callid SecondCallid,
a.[segStart_dateTime] FirstCallTime,
b.[segStart_dateTime] SecondCallTime,
DateDiff(second, a.[segStart_dateTime], b.[segStart_dateTime]) as [myDiff]
FROM CallVolume.AreaGeneratedActivity a
JOIN CallVolume.AreaGeneratedActivity b on
a.calling_pty = b.calling_pty
and a.[segStart_dateTime] < b.[segStart_dateTime]
and dbo.getdateonly(a.segStart_dateTime) = dbo.getdateonly(b.segStart_dateTime)
WHERE ABS(DateDiff(second, a.[segStart_dateTime], b.[segStart_dateTime])) > 60
and ABS(DateDiff(second, a.[segStart_dateTime], b.[segStart_dateTime])) <= 1800
以及返回的内容是:
|What_Tech|FirstCallid|SecondCallid|FirstCallTime|SecondCallTime|myDiff | Tech1 | 21134601 | 21136023 | 09:19:41 | 09:20:43 | 62 | Tech1 | 21134601 | 21134507 | 09:19:41 | 09:19:41 | 886 | Tech1 | 21134601 | 21134602 | 09:19:41 | 09:34:27 | 887
我想要的是不同的FirstCallids:
|What_Tech|FirstCallid|SecondCallid|FirstCallTime|SecondCallTime|myDiff | Tech1 | 21134601 | 21134676 | 09:19:41 | 09:20:43 | 62 | Tech1 | 21136023 | 21136024 | 09:34:27 | 09:35:27 | 1
以下是表中的一些示例数据:
INSERT [dbo].[TestData](callid, What_Tech, segStart_dateTime, segStop_dateTime, duration)
SELECT 21134601, N'Tech1', '20120307 09:19:41', '20120307 09:20:35', 54 UNION ALL
SELECT 21134676, N'Tech1', '20120307 09:20:43', '20120307 09:21:30', 47 UNION ALL
SELECT 21136023, N'Tech1', '20120307 09:34:27', '20120307 09:36:54', 147 UNION ALL
SELECT 21148838, N'Tech1', '20120307 12:00:29', '20120307 12:02:05', 96 UNION ALL
SELECT 21149159, N'Tech1', '20120307 12:04:32', '20120307 12:05:46', 74 UNION ALL
SELECT 21163170, N'Tech1', '20120307 14:50:08', '20120307 14:52:36', 148
请注意,返回内容和我想要的样本数据仅仅是示例,而不是直接来自INSERT语句中给出的示例数据
发布的查询(一旦我删除了calling_party
的{{1}}的连接条件,并且将函数调用更改为内联计算),根据提供的示例数据生成这些结果:
INSERT
鉴于此,您能否根据您提供的实际样本数据来定义您期望的结果,而不是从我们看不到的略微不同的数据集中显示所需的结果?
答案 0 :(得分:2)
CROSS APPLY将使联接仅从b7
获取第一行,从而消除您遇到的重复问题。 BUT!如果允许calling_pty的第三个调用表示为pair(second_call,third_call),这只会产生令人满意的结果,即SecondCall可以是其他行中的FirstCall。如果你想在秒之后消除所有电话,你将需要不同的方法。
Here is Sql Fiddle DEMO version.
select
a.What_Tech,
a.callid FirstCallid,
b.Callid SecondCallid,
a.[segStart_dateTime] FirstCallTime,
b.[segStart_dateTime] SecondCallTime,
DateDiff(second, a.[segStart_dateTime], b.[segStart_dateTime]) as [myDiff]
from testdata a
cross apply
(
select top 1
CallId,
[segStart_dateTime]
from testdata
-- Filtering by a.calling_pty is missing
where testdata.segStart_dateTime > dateadd (second, 60, a.segStart_dateTime)
and testdata.segStart_dateTime <= dateadd (second, 1800, a.segStart_dateTime)
order by testdata.segStart_dateTime
) b
答案 1 :(得分:0)
例如,您可以GROUP BY
首次呼叫ID(以及您希望选择的仅与第一个呼叫ID相关联的所有列),并选择MIN(b.callid)
。但是,您需要子查询或来自此最小第二个呼叫ID的其他联接才能到达第二个呼叫ID的任何属性,因为从逻辑上讲,第一个呼叫不能唯一地标识第二个呼叫。