2017-07-10 203 views
-8

樣本數據:多案例陳述方案

+--------+-----------+----------+------------+-------+ 
| CaseID | StartDate | EndDate | ReviewDate | Event | 
+--------+-----------+----------+------------+-------+ 
|  56 | 7/2/2017 | 7/2/2017 | 7/2/2017 | pre | 
|  56 |   |   |   | post | 
+--------+-----------+----------+------------+-------+ 

我需要寫一個case statement當事件=崗位和開始日期,結束日期和REVIEWDATE爲空,我需要考慮事件的日期=前其他職位

我該如何處理這種情況下

+2

請提供樣品數據和期望的輸出 –

+3

哪裏是你的企圖? – Eric

+7

歡迎來到Stack Overflow。請花點時間參加[參觀]並閱讀[問]以獲得更好的答案。 –

回答

0

你只需要一個自我加入...沒有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' 
0

你可以做自己留下後值加盟,就得到如下結果:

Select t1.CaseID, case when coalesce(t2.StartDate, t2.EndDate, t2.ReviewDate) is null then t1.StartDate else t2.StartDate end as StartDate 
    ,case when coalesce(t2.StartDate, t2.EndDate, t2.ReviewDate) is null then t1.EndDate else t2.EndDate end as EndDate 
    ,case when coalesce(t2.StartDate, t2.EndDate, t2.ReviewDate) is null then t1.ReviewDate else t2.ReviewDate end as ReviewDate 
    from #table t1 
left join #table t2 
    on t1.CaseID = t2.CaseID 
where t1.[Event] = 'pre' 
    and t2.[Event] = 'post'