如何通过CTE获取最新日期

时间:2017-01-27 23:06:32

标签: sql sql-server join common-table-expression

我有这个公用表表达式,它应该为在“2015-07-01”之后接收服务'S'的客户提取数据,并且最新注册'e'日期应该在'2015-07-01'之前,但结果set包括在“2015-07-01”之后重新注册的客户,因为他们也有多个类似服务的注册。不确定要包括哪些条款以确保他们的最新注册开始日期是在“2015-07-01”之前。

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

1 个答案:

答案 0 :(得分:0)

这有用吗?

替换and e.BeginDate < '2015-07-01'
-- ...
and e.BeginDate = (select max(e_i.BeginDate)
                   from enrollment e_i
                   where e_i.BeginDate < '2015-07-01')
-- ...