在MS SQL Server中,有两个表,' T1'和' T2',有一个公共字段' ID(PK)',其中ID是唯一的,但对于相同的ID记录,T1和T2中的日期可能不同,ABC或DEF的内容也可能不同例如:
----------
T1:
----------
ID Date A B C
----------
55 12/1/17 Jim Smith Male
77 12/2/17 Jim Green Male
99 10/3/17 Kate Lee Male
T2:
----------
ID Date D E F
----------
55 12/1/17 Jim Smith Male
77 10/2/16 James Jr Male
99 12/25/17 Kathy Lee Male
我想基于ID获得某种形式的连接表,并根据最新日期选择ABC或DEF,在这种情况下,我想拥有
----------
ID Date join1| join2 | join3
----------
55 12/1/17 Jim Smith Male
77 12/2/17 Jim Green Male
99 12/25/17 Kathy Lee Male
这可能吗?
到目前为止我想出的是,有点乏味:我首先做了一个完整的外部加入:
select * from T1 full outer join T2 on T1.ID = T2.ID
拥有以下内容:
ID Date A B C Date2 D E F
----------
55 12/1/17 Jim Smith Male 12/1/17 Jim Smith Male
77 12/2/17 Jim Green Male 10/2/16 James Jr Male
99 10/3/17 Kate Lee Male 12/25/17 Kathy Lee Male
然后我尝试使用case when then else
来选择ABC或DEF字段,这些字段看起来非常难看,我担心性能。
select T1.ID,
case when T1.Date > T2.Date then T1.Date else T2.Date END as Date
case when T1.Date > T2.Date then T1.A else T2.D END as Join1
case when T1.Date > T2.Date then T1.B else T2.E END as Joni2
case when T1.Date > T2.Date then T1.C else T2.F END as Join3
from RESULT_TABLE
是否可以执行以下操作:
select T1.ID,
case when T1.Date > T2.Date then
T1.Date, T1.A as Join1, T1.B as Join2, T1.C as Join3
else
T2.Date, T2.D as Join1 , T2.E as Join2, T2.F as Join3
END
from RESULT_TABLE
答案 0 :(得分:0)
一种方法使用case
:
select t1.id,
(case when t1.date >= t2.date then t1.date else t2.date end) as date,
(case when t1.date >= t2.date then t1.a else t2.a end) as a,
(case when t1.date >= t2.date then t1.b else t2.a end) as b,
(case when t1.date >= t2.date then t1.c else t2.a end) as c
from t1 join
t2
on t1.id = t2.id;
如果你不喜欢所有的case
表达式,你可以这样做:
select t1.*
from t1 join
t2
on t1.id = t2.id and t1.date >= t2.date
union all
select t2.*
from t1 join
t2
on t1.id = t2.id and t1.date < t2.date;
注意:您可能希望列出列而不是使用select *
。此版本假定两个表具有完全相同的列,顺序相同,具有兼容类型。
答案 1 :(得分:0)
当然,
Select t1.Id,
case when t1.Date > t2.Date then t1.Date else t2.Date end date,
case when t1.Date > t2.Date then t1.A else t2.D end AD,
case when t1.Date > t2.Date then t1.B else t2.E end BE,
case when t1.Date > t2.Date then t1.C else t2.F end CF
From T1 join T2 on t2.Id = t1.Id