简体   繁体   中英

MS-ACCESS / SQL - How to apply where clause in multiple conditions

SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
) 
AND 
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
) 
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
) 
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);

I am using the above SQL to achieve below 3 items:-

  1. Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only
  2. Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.
  3. If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.

However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3? Table and Query snapshots are attached. Thanks in advance!

Table

Query

What you need to do is to check if the total number of times a part is used in all pieces of Equipment is equal to the total number of times a part is used by either Equipment A or B:

SELECT S.StorageID, S.ComputerPartNumber, S.EquipmentName, S.Result
FROM Stock AS S
WHERE 
(SELECT COUNT(*) FROM Stock AS S1 WHERE S1.ComputerPartNumber=S.ComputerPartNumber)
=(SELECT COUNT(*) FROM Stock AS S2 WHERE S2.ComputerPartNumber=S.ComputerPartNumber AND S2.EquipmentName IN("EquipmentA","EquipmentB"))

Regards,

You can use not exists :

select s.*
from stock as s
where not exists (select 1
                  from stock as s2
                  where s2.ComputerPartNumber = s.ComputerPartNumber and
                        s2.EquipmentName not in ("EquipmentA", "EquipmentB")
                 );

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