我有一个有两个表的数据库。一个Call_Info
表,其中包含有关传入/传出呼叫的详细信息,并具有名为Call_ID
的唯一ID。我有一个第二个表链接并称为After_Call_Work
表。
每次通话只有一次通话后工作记录。数据集有点混乱,对于同一个呼叫,有时会有3或4个呼叫工作记录。在进行查询时,如何只检索该特定呼叫的最早呼叫后工作记录而忽略其余的呼叫?我想象使用SQL函数First_Value但它似乎不是正确的。
使用Microsoft SQL Server 2012。
有什么想法吗?
答案 0 :(得分:0)
这可以通过利用Window Function
WITH call_List
AS
(
SELECT Call_ID, OtherColumns, DateColumn,
ROW_NUMBER() OVER (PARTITION BY Call_ID ORDER BY DateColumn ASC) rn
FROM After_Call_Work
)
SELECT a.*, b.OtherColumns, b.DateColumn
FROM Call_Info a
INNER JOIN call_List b
ON a.Call_ID = b.Call_ID
WHERE b.rn = 1
答案 1 :(得分:0)
您应该可以使用select top
,如下所示:
SELECT TOP 1
FROM call_info ci JOIN after_call_work acw ON ci.call_id=acw.call_id
ORDER BY acw.work_time DESC
WHERE ci.call_id=<your_call_id>
答案 2 :(得分:0)
WITH g AS (SELECT ROW_NUMBER() OVER (PARTITION BY callid
ORDER BY date ASC) AS row,* from after_call_work
select * from call_info cinfo inner join g on
cinfo.callid = g.callid and g.row=1