多个案例陈述情景

时间:2017-07-10 17:44:49

标签: sql sql-server sql-server-2012

示例数据:

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

当event = post和startdate,enddate和reviewdate为null时我需要写一个case statement我需要考虑event = pre else post中的日期

我该如何处理这种情况

2 个答案:

答案 0 :(得分:0)

你只需要一个自我加入......没有案例陈述,因为总有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'

答案 1 :(得分: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'