你只需要一個自我加入...沒有case語句,因爲總有1周前和1篇文章。這有兩種方法。
這查詢不只是你的要求說
declare @table table (CaseID int, StartDate date, EndDate date, ReviewDate date, [Event] varchar(64))
insert into @table
values
(56,'20170702','20170702','20170702','pre'),
(56,NULL,NULL,NULL,'post'),
(57,'20170704',NULL,NULL,'pre'),
(57,'20170705','20170705','20170705','post'),
(58,NULL,'20170709',NULL,'pre'),
(58,'20170709',NULL,'20170709','post')
select
t1.CaseID
,case when t1.startDate is null and t1.EndDate Is Null and t1.ReviewDate is null then t2.StartDate else t1.StartDate end as StartDate
,case when t1.startDate is null and t1.EndDate Is Null and t1.ReviewDate is null then t2.EndDate else t1.EndDate end as EndDate
,case when t1.startDate is null and t1.EndDate Is Null and t1.ReviewDate is null then t2.ReviewDate else t1.ReviewDate end as ReviewDate
from
@table t1
left join
@table t2 on
t2.CaseID = t1.CaseID
and t2.Event <> t1.Event
where
t1.[Event] = 'post'
這一個基本合併的行爲NULL日期
select
t1.CaseID
,coalesce(t1.StartDate, t2.StartDate) as StartDate
,coalesce(t1.EndDate,t2.EndDate) as EndDate
,coalesce(t1.ReviewDate,t2.EndDate) as ReviewDate
from
@table t1
left join
@table t2 on
t2.CaseID = t1.CaseID
and t2.Event <> t1.Event
where
t1.[Event] = 'post'
請提供樣品數據和期望的輸出 –
哪裏是你的企圖? – Eric
歡迎來到Stack Overflow。請花點時間參加[參觀]並閱讀[問]以獲得更好的答案。 –