Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Finding Missing Records
Message
 
 
À
31/10/2017 12:54:13
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Versions des environnements
SQL Server:
SQL Server 2012
Divers
Thread ID:
01655302
Message ID:
01655305
Vues:
36
I misread your original requirement
;with allCombinations as (select I.*, B.* from Items I, Branches B)

select AC.* from allCombinations AC where not exist (select 1 from BranchItems BI where BI.ItemId = AC.ItemID and BI.BranchId = AC.BranchID)
>>>Hi,
>>>
>>>I've got a mental block at the moment (I've done this many times before) and hoping someone can break the block down for me.
>>>
>>>
>>>use test
>>>
>>>create table Items
>>>(ItemId int,
>>>ItemCode char(1))
>>>
>>>insert into Items values (1, 'A')
>>>,(2, 'B')
>>>,(3, 'Z')
>>>
>>>create table Branches
>>>(BranchID int,
>>>BranchCode char(1))
>>>
>>>insert into Branches values (1, 'C')
>>>,(2, 'D')
>>>
>>>create table BranchItems
>>>(BranchItemId int
>>>,ItemID int
>>>,BranchID int
>>>,QtyOnHand int)
>>>
>>>insert into BranchItems values (1, 1, 1, 10)
>>>,(2,1,2,15)
>>>,(3,2,1,20)
>>>
>>>select ItemCode, BranchCode, QtyOnHand
>>>from branchitems
>>>inner join Items on BranchItems.itemID = Items.ItemId
>>>inner join Branches on BranchItems.BranchID = Branches.BranchID
>>>
>>>/*
>>>ItemCode	BranchCode	QtyOnHand
>>>A	C	10
>>>A	D	15
>>>B	C	20
>>>*/
>>>
>>>drop table Items
>>>drop table Branches
>>>drop table BranchItems
>>>
>>>I need to find items that are missing records in the BranchItems table.
>>>
>>>For example in the code above, ItemCode B has no record for BranchCode D.and ItemCode Z has no records in BranchItems at all.
>>>
>>>Thanks for any help
>>
>>For the missing items from BranchItems table:
>>
>>select I.* from Items I where not exists (select * from BranchItems BI where BI.ItemCode = I.ItemCode)
>>
>>and you can use similar code for finding other missing rows.
>
>Thanks but there is no column called ItemCode in BranchItems.
>I tried changing it to this:
>
>
select I.* 
>from Items I 
>where not exists (select * 
>					from BranchItems BI 
>					where BI.ItemID = I.ItemID)
>
>but that returns nothing.
>
>The query should show me the item ID and the Branch ID that are missing (e.g. 2,2 and 3,1, and 3,2)
>
>< later >
>
>This seems to work:
>
>
select I.ItemID, B.BranchID, I.ItemCode, B.BranchCode 
>from Items I, Branches B
>where not exists (select ItemCode, BranchCode, QtyOnHand, BI.ItemID, BI.BranchID
>						from branchitems BI
>						inner join Branches on BI.BranchID = Branches.BranchID
>						inner join Items ON BI.ItemId = Items.ItemID
>					where BI.ItemID = I.ItemID
>						and BI.BranchID = B.BranchID)
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform