Sql 如何使用CTE获取最新日期
我有一个通用的表表达式,它应该为在“2015-07-01”之后收到服务的客户提取数据,最新注册日期“e”应该在“2015-07-01”之前,但结果集包括在“2015-07-01”之后重新注册的客户,因为他们也有多个类似注册的服务。不确定要包括哪些条款,以确保其最新报名开始日期在“2015-07-01”之前Sql 如何使用CTE获取最新日期,sql,sql-server,join,common-table-expression,Sql,Sql Server,Join,Common Table Expression,我有一个通用的表表达式,它应该为在“2015-07-01”之后收到服务的客户提取数据,最新注册日期“e”应该在“2015-07-01”之前,但结果集包括在“2015-07-01”之后重新注册的客户,因为他们也有多个类似注册的服务。不确定要包括哪些条款,以确保其最新报名开始日期在“2015-07-01”之前 WITH PhoneLog AS ( select s.ProvidedToEntityID, concat (c.FirstName,' ', C.LastName) as ClientN
WITH PhoneLog AS
(
select s.ProvidedToEntityID,
concat (c.FirstName,' ', C.LastName) as ClientName,
ecp.CellPhone,
ecp.HomePhone,
case ecp.PhoneVoiceOptIn
when 1 then 'Yes'
when 2 then 'No'
Else 'Unknown'
End as ContactViaPhone,
S.BeginDate ServiceStart,
e.BeginDate EnrollmentBeginDate,
case
when Dateadd(YY,Datediff(YY,c.birthdate,getdate()), c.birthdate)> getdate()
then datediff(YY,birthdate,getdate())
else datediff(YY,birthdate,getdate())
end as 'Current Age',
e.X_ProgramStatus as 'program Status',
ROW_NUMBER () over (Partition by s.providedtoEntityID order By s.begindate Desc ) as ClientCount
from
Client c
Join Service s on c.EntityID = s.ProvidedByEntityID
join servicetype st on s.ServiceTypeID = st.ServiceTypeID
join Enrollmentmember Em on c.EntityID = em.ClientID
join enrollment e on em.EnrollmentID = e.EnrollmentID
join Entitycontactpreference ecp on c.entityid = ecp.entityid
where s.BeginDate >= '2015-07-01'
and e.BeginDate < '2015-07-01'
--and s.BeginDate>e.BeginDate
and ecp.PhoneVoiceOptIn = 1
)
SELECT
ProvidedToEntityID,
ClientName,
[Current Age],
cellphone,
Homephone,
ContactViaPhone,
ServiceStart,
EnrollmentBeginDate,
ClientCount,
[program Status]
FROM
PhoneLog
WHERE
ClientCount = 1
这行吗
将e.BeginDate<'2015-07-01'替换为
我不知道你为什么要用CTE。它似乎并没有给你增加什么。我建议通过ENTROLLMENT DESC RNK通过客户机ID顺序在分区上添加某种类型的行数。。。然后只过滤到RNK1以获得最新的结果。你能提供样本数据和预期结果吗?感谢大家的努力,所以我使用了<而不是=。祝福你!
-- ...
and e.BeginDate = (select max(e_i.BeginDate)
from enrollment e_i
where e_i.BeginDate < '2015-07-01')
-- ...