简体   繁体   中英

Return all inactive items from Table B for each item in Table A

Not sure if I can explain this well in words..

I want to find all items in Table B that have ALL items inactive for each item in Table A. Let's say Table A just has column "item" and Table B has columns "item" and "active"

Table A              Table B 
A                     A | 1
A                     A | 1  
A                     B | 1
B                     B | 0
B                     C | 0
B                     C | 0
C                     D | 0 
C                     E | 1
D                     
E
F

In that example, it should return C and D.

I managed to join tables A and B together with a group by clause but not sure where to go from there. Tried looking around and only found answers where the other table's value doesn't exist so you can use "NOT IN" but that doesn't seem to work here.

Any help would be appreciated!

Use NOT EXISTS :

select distinct a.item
from table_A a
where not exists (select 1 from table_B b where b.item = a.item and b.status = 1);

You can join the tables and use the HAVING clause to make the comparison like this:

SELECT ta.Item
FROM TableA tA
LEFT JOIN TableB tB
ON tA.Item=tB.Item
GROUP BY tA.Item
HAVING SUM(tB.Inactive)=COUNT(tb.Inactive)

This would give you a distinct list of Items in TableA

The above query assumes 1 is Inactive and 0 is Active. If your data is opposite (which it looks like it is), you could instead say:

SELECT ta.Item
FROM TableA tA
LEFT JOIN TableB tB
ON tA.Item=tB.Item
GROUP BY tA.Item
HAVING SUM(tB.Inactive)=0

This would also return Item F as it doesn't have a value in table b to SUM. Just flip the LEFT JOIN to an INNER JOIN if you don't want Item F to return.

If you need to return back all instances in TableA, you could use a subquery and join to that:

SELECT ta.Item
FROM TableA tA
LEFT JOIN (SELECT ITEM, SUM(ACTIVE) Sum0 FROM TableB GROUP BY ITEM)tB
ON tA.Item=tB.Item
WHERE tB.Sum0 = 0 
/*or tB.Sum0 is null would give you Item F*/

I believe you would just need to join the tables together on table name and filter to only value of 0 on the active column.

SELECT B.*
  FROM TableA A INNER JOIN TableB B ON A.item = B.item
 WHERE B.active = 0

Does that get you what you need?

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