从两个 table 创建一个视图,其中 case 和 sum 在一个 table 上

Creating a view from two tables, with case and sum on one table

我在尝试从两个 table 创建视图时遇到了一些麻烦,其中包括第一个 table 的总和 + 大小写。我尝试了多种不同的joins/unions,我可以just XTS table过来,或者just案例计数方案有效,但我无法同时获得。

这是 table。对于 Table 1,UWI 是非唯一的。对于 Table 2,UWI 是唯一的。 new_view 是我希望实现的观点。

TABLE 1

UWI ET
1   A
1   B
1   B
2   B
2   C
2   C

TABLE 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;

你的样本 select 与你的样本数据不匹配,所以这是一个猜测,但我认为你只需要将聚合移动到 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