我有以下查询:
select * from [lead].[ContactFeedback] cf
where cf.LeadId in
(select LeadId from [lead].[LeadDetails]
where TeleportReference in (122096,
122097,
122098))
order by LeadId Desc
结果是这样的:
FeedbackDate LeadId
2015-01-23 16:25:13.547 95920
2015-01-23 16:25:38.960 95919
2015-01-23 16:25:19.393 95917
2015-01-23 16:25:32.837 95916
2015-01-23 16:25:59.840 95914
2015-01-23 16:26:08.840 95913
2015-01-23 16:15:01.933 95910
2015-01-23 16:22:04.820 95910
2015-01-23 16:24:40.477 95909
2015-01-23 16:24:03.523 95908
2015-01-23 16:16:44.290 95908
2015-01-23 16:17:16.047 95907
2015-01-23 16:25:11.783 95907
我想列出每个LeadId的所有前1名(最近的反馈日期)。如何在SQL Server中实现此目的?
答案 0 :(得分:1)
select LeadId, Max(FeedbackDate)
from [lead].[ContactFeedback] cf
where cf.LeadId in
(select LeadId from [lead].[LeadDetails]
where TeleportReference in (122096, 122097, 122098))
group by LeadId
order by LeadId Desc
答案 1 :(得分:0)
使用Window Function
select leadid,feedbackdate from (
select row_number() over(partition by leadid order by feedbackdate desc) rn,*
from yourtable) a
where rn=1
答案 2 :(得分:0)
您可以执行子查询以获取每个LeadId的最大FeedBackDate。然后将详细信息表加入其中。
select cf.*
from [lead].[ContactFeedback] cf
join (select LeadId, max(FeedBackDate) maxFeedBackDate
from [lead].[ContactFeedback]
group by LeadId) as maxes
on cf.LeadId = maxes.LeadId
and cf.FeedBackDate = maxes.maxFeedBackDate
where cf.LeadId in
(select LeadId
from [lead].[LeadDetails]
where TeleportReference in (122096,
122097,
122098)
)
order by cf.LeadId Desc