我试图只选择最近的calldatetime并在我的结果中显示,有人可以帮忙吗?我需要结果只显示最新的更新记录
SELECT
ROW_NUMBER() OVER (PARTITION BY l.phonenum ORDER BY h.calldatetime) as rn,
h.HistoryID,
l.ProjectID,
h.ProjName,
l.CompanyName,
l.Phonenum,
l.fname,
l.lname,
l.Address1,
l.Address2,
l.Address3,
l.Town,
l.Postcode,
l.county,
h.CallDateTime,
cb.CBDatetime,
l.apptdate,
l.appttime,
h.CRC,
c.Description,
a.Firstname + ' ' + a.Lastname AS AgentName,
l.Notes
FROM
History h inner join
cmp_UtilityTrade l on h.PhoneNum = l.Phonenum left outer join
CRC c on c.CRC = h.CRC left outer join
Agent a on a.AgentID = h.AgentID left outer join
CallBack cb on cb.DialID = h.DialID
WHERE
h.calldatetime BETWEEN '2016-05-01 00:00:00' AND '2016-06-15 23:00:00'
ORDER BY
l.Phonenum
答案 0 :(得分:1)
看起来您已经按照您需要的方式设置了row_number() over
窗口功能。假设它返回正确的值,您只需要按rn
值过滤结果。只需将现有查询放在CTE中,并按如下方式过滤结果:
with cte as (<your_query_without_order_by_phonenum>)
select *
from cte
where rn = 1
order by phonenum
另请注意,您可能希望将order by l.Phonenum
子句移到CTE之外,并将其放在外部查询中。
修改强>
如评论中所述,您可能还必须将order by
窗口函数中的row_number()
子句修复为h.calldatetime DESC
。