2017-07-10 7 views
-8

サンプルデータ:私はcase statementイベント=ポストとSTARTDATE、終了日及びREVIEWDATEは=私はイベントの日付を考慮する必要があるnullの前、他の記事を書くために必要複数のcase文のシナリオ

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

このシナリオはどのように処理できますか

+2

サンプルデータと希望の出力を提供してください –

+3

あなたの試行はどこですか? – Eric

+7

ようこそスタックオーバーフローへ。しばらく時間を取って[ツアー]を受けてください。また、[質問]を読んで質問に答えてください。 –

答えて

0

自己紹介... no case文が必要なのは、常に前1件と1件です。ここには2つの方法があります。

このクエリは、ちょうどあなたの要件が

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' 

を述べたものをこの1つは基本的に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'