多个案例陈述场景
Posted
技术标签:
【中文标题】多个案例陈述场景【英文标题】:Multiple Case Statements Scenario 【发布时间】:2017-07-10 17:44:48 【问题描述】:样本数据:
+--------+-----------+----------+------------+-------+
| CaseID | StartDate | EndDate | ReviewDate | Event |
+--------+-----------+----------+------------+-------+
| 56 | 7/2/2017 | 7/2/2017 | 7/2/2017 | pre |
| 56 | | | | post |
+--------+-----------+----------+------------+-------+
当 event=post 和 startdate、enddate 和 reviewdate 为空时,我需要写一个 case statement
我需要考虑 event=pre else post 中的日期
我该如何处理这种情况
【问题讨论】:
请提供样本数据和所需的输出 你的尝试在哪里? 欢迎来到 Stack Overflow。请花点时间发送tour 并阅读How to Ask 以获得更好的问题解答。 尽量避免图片,因为我们无法复制文字。 每个案例 ID 是否只有 1 个且始终有 1 个前置和后置事件,还是一个案例 ID 可以有多个前置或后置事件? 【参考方案1】:您可以使用 post 值进行 self left join 并得到如下结果:
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'
【讨论】:
【参考方案2】:您只需要一个自我加入...没有案例陈述,因为总是有 1 个 pre 和 1 个 post。这里有两种方法。
此查询符合您的要求
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'
【讨论】:
以上是关于多个案例陈述场景的主要内容,如果未能解决你的问题,请参考以下文章