问题描述
我在尝试从两个表创建视图时遇到了一些麻烦,其中包括第一个表的 sum + case。我尝试了多个不同的连接/联合,我可以只是让 XTS 表过来,或者只是案例计数场景可以工作,但我不能同时获得.
这是表格。对于表 1,UWI 是非唯一的。对于表 2,UWI 是唯一的。 new_view 是我希望为我的观点实现的目标。
表 1
UWI ET
1 A
1 B
1 B
2 B
2 C
2 C
表 2
UWI XTS
1 10
2 20
3 10
4 30
new_view
UWI XTS B_COUNT C_COUNT
1 10 4 3
2 20 3 4
3 10 4 5
4 30 3 2
这是我目前正在使用的。
CREATE VIEW new_view AS
SELECT t1.UWI,sum(case when t1.ET='B' then 1 else 0 end) as B_COUNT,sum(case when t1.ET='C' then 1 else 0 end) as C_COUNT,sum(case when t1.ET='D' then 1 else 0 end) as D_COUNT,sum(case when t1.ET='E' then 1 else 0 end) as E_COUNT,sum(case when t1.ET='F' then 1 else 0 end) as F_COUNT
FROM TABLE_1 t1
INNER JOIN (SELECT t2.UWI,t2.XTS AS TSC
from TABLE_2 t2)
on t1.UWI = t2.UWI
group by t1.UWI;
解决方法
您的样本选择与您的样本数据不匹配,因此这是一个猜测,但我认为您只需要将聚合移动到 apply()
select t2.UWI,t2.XTS,s.*
from Table_2 t2
outer apply (
select
sum(case when t1.ET='B' then 1 else 0 end) as B_COUNT,sum(case when t1.ET='C' then 1 else 0 end) as C_COUNT,sum(case when t1.ET='D' then 1 else 0 end) as D_COUNT,sum(case when t1.ET='E' then 1 else 0 end) as E_COUNT,sum(case when t1.ET='F' then 1 else 0 end) as F_COUNT
from table_1 t1
where t1.UWI = t2.UWI
group by t1.UWI
)s