sql - EXISTS and NOT EXISTS in a correlated subquery -
sql - EXISTS and NOT EXISTS in a correlated subquery -
i've been trying work out how particular query day or , has gotten point need outside help. hence question.
given next data;
declare @data table ( orgid int, thingid int ) declare @replacementdata table ( oldthingid int, newthingid int ) insert @data (orgid, thingid) values (1, 2), (1, 3), (1, 4), (2, 1), (2, 4), (3, 3), (3, 4) insert @replacementdata (oldthingid, newthingid) values (3, 4), (2, 5)
i want find organisation has "thing" has been replaced denoted in @replacementdata
table variable. i'd want see org id, thing have has been replaced , id of thing should replace it. illustration given info above, should see;
org id, thing id, replacement thing id org doesn't have should have 1, 2, 5 -- org 1 has 2, not 5
i've had many attempts @ trying working, , can't seem head around how go it. next couple of attempts, think way off;
-- effort using correlated subqueries , exists clauses -- show orgs have old thing, not new thing -- ideally, limit results orgid, oldthingid , newthingid should have select * @data d exists (select * @data oldstuff oldstuff.orgid = d.orgid , oldstuff.thingid in (select oldthingid @replacementdata)) , not exists (select * @data oldstuff oldstuff.orgid = d.orgid , oldstuff.thingid in (select newthingid @replacementdata)) -- effort @ using bring together include old things org has (via clause) -- seek exists show missing new things. select * @data d left bring together @replacementdata rd on rd.oldthingid = d.thingid not exists ( select * @data dta inner bring together @replacementdata rep on rep.newthingid = dta.thingid dta.orgid = d.orgid ) , rd.oldthingid not null
any help on much appreciated. may going wrong, please allow me know if there improve way of tackling type of problem.
try out , allow me know.
declare @data table ( orgid int, thingid int ) declare @replacementdata table ( oldthingid int, newthingid int ) insert @data (orgid, thingid) values (1, 2), (1, 3), (1, 4), (2, 1), (2, 4), (3, 3), (3, 4) insert @replacementdata (oldthingid, newthingid) values (3, 4), (2, 5) select d.orgid, rd.* @data d bring together @replacementdata rd on d.thingid=rd.oldthingid left outer bring together @data exclude on d.orgid = exclude.orgid , rd.newthingid = exclude.thingid exclude.orgid null
sql sql-server exists correlated-subquery
Comments
Post a Comment