微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。