将 tableA 中的 select 查询结果添加为 tableB 中的新列

问题描述

我正在通过以下查询连接两个表来创建一个新表:

select a.name,a.number,b.id,b.sub_num
    from tableA a left join
         tableB b
         on a.number = concat(id,'-',Cast(sub_num as varchar);

在这里,我想在新表中添加一个 new column,它是 tableA 上的选择查询结果。

表格数据如下所示: enter image description here

我正在尝试使用以下不正确的查询,因为它给了我多行。我需要条件 dext_id = 17501 的 dext_number 总和,并按名称和数字列分组。

select a.name,b.sub_num,(select sum(dext_number) from tableA where dext_id = 17501 group by name,number) as newcol 
     from tableA a left join tableB b 
  on a.number = concat(id,Cast(sub_num as varchar);

在此处添加此列的最佳方法是什么?

解决方法

使用以下查询

select a.name,a.number,b.id,b.sub_num,(select sum(dext_number) over(partition by name,number) from tableA 
where dext_id = 'xyz' limit 1) as newcol 
from tableA a 
left join tableB b on a.number = concat(id,'-',Cast(sub_num as varchar);

如果您想要查询图像的确切输出,请使用以下查询

select L.name,L.number,L.dext_id,L.dext_number,case when L.num > 1 then newcol
  else NULL
  end as newcol
from
(select *,count(dext_number) over(partition by name,number) as num,sum(dext_number) over(partition by name,number) as newcol
  from tableA) L left join tableA R on L.dext_id = R.dext_id and L.name= R.name and L.number = R.number and L.dext_number = R.dext_number

第一个查询和tableB的组合如下

select a.name,(select
  case when L.num > 1 then newcol
  else NULL
  end as newcol
from
(select *,number) as newcol
  from Test) L left join Test R on L.dext_id = R.dext_id and L.name= R.name and L.number = R.number and L.dext_number = R.dext_number limit 1) as newcol 
from tableA a 
left join tableB b on a.number = concat(id,Cast(sub_num as varchar);