简体   繁体   中英

add select query result from tableA as a new column in tableB

I am creating a new table from joining two tables through below query:

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

Here, I want to add a new column into the new table which is select query result on tableA.

The table data would be something like below: enter image description here

I am trying to use below query which is not correct as it is giving me multiple rows. I need sum of dext_number for condition dext_id = 17501 and group by of name and number columns.

select a.name, a.number, b.id, 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);

What is the best way to add this column here?

use following query

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

If you want the exact output of the query image, use the following query

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

And the combination of the first query with tableB will be as follows

select a.name, a.number, b.id, b.sub_num, (select
  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 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM