【发布时间】:2017-01-27 23:06:32
【问题描述】:
我有这个公用表表达式,它应该为在“2015-07-01”之后收到服务“S”的客户提取数据,并且最新注册“e”日期应该在“2015-07-01”之前,但结果set 包括在“2015-07-01”之后重新注册的客户,因为他们也有多次注册等服务。不确定要包含什么条款以确保他们的 LATEST 注册开始日期早于“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
【问题讨论】:
-
我不确定您为什么要使用 CTE。它似乎没有为你添加任何东西。我建议添加某种类型的 ROW_NUMBER OVER (PARTITION BY Client ID ORDER BY ENTROLLMENT DESC) RNK ...然后过滤到仅 RNK1 以获得最新的。
-
能否提供样本数据和预期结果?
标签: sql sql-server join common-table-expression