[英]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" 我想在表B中找到所有对表A中的每个项目都无效的所有项目。假设表A仅具有“项目”列,而表B具有“项目”和“活动”列
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. 在该示例中,它应返回C和D。
I managed to join tables A and B together with a group by clause but not sure where to go from there. 我设法将表A和B与group by子句连接在一起,但不确定从那里去哪里。 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.
尝试环顾四周,仅在其他表的值不存在的情况下找到答案,因此您可以使用“ NOT IN”,但这似乎在这里不起作用。
Any help would be appreciated! 任何帮助,将不胜感激!
Use NOT EXISTS
: 使用
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: 您可以联接表并使用
HAVING
子句进行如下比较:
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 这将为您提供TableA中不同的项目列表
The above query assumes 1 is Inactive and 0 is Active. 上面的查询假设1为非活动状态,0为活动状态。 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. 这也将返回项目F,因为它在表b中不具有SUM值。 Just flip the
LEFT JOIN
to an INNER JOIN
if you don't want Item F to return. 如果您不希望F项返回,只需将
LEFT JOIN
切换为INNER JOIN
。
If you need to return back all instances in TableA, you could use a subquery and join to that: 如果需要返回TableA中的所有实例,则可以使用子查询并加入该子查询:
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. 我相信您只需要在表名上将表连接在一起,并在活动列上将其过滤为仅值为0。
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? 那能给您您所需要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.