[英]How to add a counting column for specific values (as sub-select)
I have a query that I want to add a colum to.我有一个要向其中添加列的查询。 It should contain the amount of how many times a value of a specific column appears in that table.
它应该包含特定列的值在该表中出现的次数。
My current attempt我目前的尝试
SELECT cleaning.*,
(SELECT COUNT(*)
FROM cleaning
WHERE column_b = cleaning.column_b)
AS multicleanamount
FROM cleaning
is counting every single row as it is just comparing a column with same column - I understand the reason.正在计算每一行,因为它只是将一列与同一列进行比较 - 我理解原因。 So the current (wrong) result is
所以当前(错误)的结果是
column_a![]() |
column_b![]() |
multicleanamount![]() |
---|---|---|
12 ![]() |
300 ![]() |
7 ![]() |
13 ![]() |
321 ![]() |
7 ![]() |
14 ![]() |
300 ![]() |
7 ![]() |
15 ![]() |
330 ![]() |
7 ![]() |
16 ![]() |
330 ![]() |
7 ![]() |
17 ![]() |
351 ![]() |
7 ![]() |
18 ![]() |
330 ![]() |
7 ![]() |
What I am missing now is how do I tell the sub-Select to compare with the current value of cleaning.column_b
from the very first line?我现在缺少的是如何告诉子选择与第一行中的
cleaning.column_b
的当前值进行比较? (which is in the cleaning.*
) (这是在
cleaning.*
)
2bh it was pretty easy in my head at first and it also would be if I'd compare to a static value like '300'
but that table has 74 K entries. 2bh 起初在我的脑海中很容易,如果我将它与像
'300'
这样的静态值进行比较,但该表有 74 K 个条目也是如此。 This has to be dynamic.这必须是动态的。
My desired output is我想要的输出是
column_a![]() |
column_b![]() |
multicleanamount![]() |
---|---|---|
12 ![]() |
300 ![]() |
2 ![]() |
13 ![]() |
321 ![]() |
1 ![]() |
14 ![]() |
300 ![]() |
2 ![]() |
15 ![]() |
330 ![]() |
3 ![]() |
16 ![]() |
330 ![]() |
3 ![]() |
17 ![]() |
351 ![]() |
1 ![]() |
18 ![]() |
330 ![]() |
3 ![]() |
I hope that is understandable.我希望这是可以理解的。 If not please tell me and I will try to specify even more.
如果不是,请告诉我,我会尝试指定更多。
Use table aliases so you can distinguish the cleaning
table in the subquery from the table in the main query.使用表别名,以便您可以将子查询中的
cleaning
表与主查询中的表区分开来。 In your query, WHERE column_b = cleaning.column_b
is comparing the column with itself, so the condition is always true and you're counting all the rows.在您的查询中,
WHERE column_b = cleaning.column_b
正在将列与其自身进行比较,因此条件始终为真并且您正在计算所有行。
SELECT c1.*,
(SELECT COUNT(*)
FROM cleaning AS c2
WHERE c1.column_b = c2.column_b)
AS multicleanamount
FROM cleaning AS c1
It may also be better to write this as a JOIN
instead of correlated subquery:将其编写为
JOIN
而不是相关子查询也可能更好:
SELECT c1.*, c2.multicleanamount
FROM cleaning AS c1
JOIN (
SELECT column_b, COUNT(*) AS multicleanamount
FROM cleaning
GROUP BY column_b
) AS c2 ON c1.column_b = c2.column_b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.