select
A.inv,
A.amt,
A.disc,
B.charges,
B.freight,
B.insurance
from TableA as A
inner join (
SELECT t.inv,
MAX(CASE WHEN t.descr = 'CHARGES' THEN t.amt ELSE NULL END) AS charges,
MAX(CASE WHEN t.descr = 'FREIGHT' THEN t.amt ELSE NULL END) AS freight,
MAX(CASE WHEN t.descr = 'INSURANCE' THEN t.amt ELSE NULL END) AS insurance
FROM TableB as t
GROUP BY t.inv) as B
on A.inv = B.inv
where charges = 100 --<< just add this
В зависимости от того, сколько строк содержит tableb.amt = 100 and descr = 'charges'
, вам может быть лучше написать запрос таким образом.
select a.inv, a.amt, a.disc,
b.amt AS charges,
c.amt AS freight,
d.amt AS insurance
from tablea a
inner join tableb b on b.inv = a.inv and b.descr = 'CHARGES' and b.amt = 100
left join tableb c on c.inv = a.inv and c.descr = 'FREIGHT'
left join tableb d on d.inv = a.inv and d.descr = 'INSURANCE'
Данные испытаний
create table tablea (inv int, amt int, disc int);
insert tablea select 1001,1500,150;
insert tablea select 1002,3000,300;
create table tableb (inv int, descr varchar(10), amt int);
insert tableb select 1001, 'CHARGES', 100;
insert tableb select 1001, 'FREIGHT', 30;
insert tableb select 1001, 'INSURANCE', 20;
insert tableb select 1002, 'CHARGES', 215;
insert tableb select 1002, 'FREIGHT', 32;
insert tableb select 1002, 'INSURANCE', 25;
выход
inv amt disc charges freight insurance
----------- ----------- ----------- ----------- ----------- -----------
1001 1500 150 100 30 20
Warning: Null value is eliminated by an aggregate or other SET operation.
(1 row(s) affected)
Примечание. При использовании предложенного второго запроса предупреждение не выводится в выходных данных