简体   繁体   English

来自一个表的SQL COUNT,其中来自另一个表的条件为真

[英]SQL COUNT from one table where condition from another table is true

Okay, so let's say I have two tables, "TableA" and "TableB". 好的,假设我有两个表“ TableA”和“ TableB”。 In Table AI have a column "C", and in Table BI have a column "D" and a column "E". 在表AI中,列“ C”,在表BI中,列“ D”和“ E”。

TableA contains a lot of rows that can contain the same value in column C. TableB contains a lot of rows, but column D has to be unique (it's the autoincrement number). TableA包含很多行,这些行可以在C列中包含相同的值。TableB包含很多行,但是D列必须是唯一的(这是自动递增的编号)。 TableB's column E also can contain the same value in different rows. TableB的E列在不同的行中也可以包含相同的值。 As well, column C and column D will contain the same numbers. 同样,C列和D列将包含相同的数字。

Example Tables 示例表

TableA

ID     C
----------
1      1
2      1
3      2

TableB

D    E
----------
1    1
2    0
3    0

Now, what I want to do is count all the rows in TableA in column C, which I have figured out how to do. 现在,我要做的是计算出C列中TableA中的所有行,我已经弄清楚该怎么做。 However, I additionally want it to only give me as a result the count of C where the equivalent value in D also has an E of "1". 但是,我还希望它仅给我C的计数,其中D中的等效值也具有E“ 1”。

So, I have tried this, but it is failing and I cannot think of what I'm doing wrong or how to fix it. 因此,我已经尝试过了,但是失败了,我无法想到自己在做什么或如何解决。 Googling for COUNT only gets me results dealing with one table. 搜寻COUNT只让我得到处理一张桌子的结果。

In my example, I want it to COUNT C where the ID number that matches in TableB column D where E = 1 (so, where TableB column D = 1), and return that as the count, so I want it to return to me (or something to this effect): 在我的示例中,我希望它返回到COUNT C,其中ID匹配在TableB列D中,其中E = 1(因此,其中TableB列D = 1),并将其作为计数返回,所以我希望它返回给我(或达到此目的的内容):

c COUNT(*) Descending 1 2 c COUNT(*)下降1 2

SELECT TableA.C, COUNT(*) FROM TableA, TableB WHERE TableB.E = 1 GROUP BY TableA.C ORDER BY COUNT(*) DESC

If that makes any sense... 如果那有意义的话...

You don't join the two tables on the column 您不将列中的两个表连接在一起

SELECT a.C, COUNT(*) FROM TableA a JOIN TableB b ON (C = D)
WHERE E GROUP BY a.C
ORDER BY COUNT(*) DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM