[英]SQL - Multiple Group By statements with counts
I'm writing a query for work in Microsoft Access. 我正在写一个在Microsoft Access中工作的查询。 The Raw table looks like this:
Raw表如下所示:
Columns 列
ColA | ColA | ColB
COLB
aa | aa | x
X
aa | aa | y
ÿ
bb | bb | x
X
bb | bb | x
X
The problem I am trying to solve is: For each distinct value in column A, what is the count of distinct values in column B? 我要解决的问题是:对于A列中的每个不同值,B列中的不同值计数是多少?
Output would be something like: 输出将类似于:
aa | aa | 2
2
bb | bb | 1
1
I would like to take it a step further and only select those where the count = 1, so : 我想更进一步,只选择count = 1的那些,所以:
bb | bb | 1
1
would be the only result. 将是唯一的结果。
I have found what I consider to be a overly complicated subquery to accomplish this, but I'm hoping someone has a more elegant solution. 我发现我认为这是一个过于复杂的子查询来完成此任务,但我希望有人能够提供一种更优雅的解决方案。
Thanks 谢谢
To select values of A
that have only one value of B
, you can use: 要选择仅具有一个
B
值的A
值,可以使用:
select t.A
from mytable as t
group by t.A
having min(t.B) = max(t.B);
This ignores NULL
values when considering duplicates. 考虑重复时,这将忽略
NULL
值。 That can be factored in if necessary. 如有必要,可以考虑这一点。 Also, the count seems redundant, because it will always be 1.
此外,该计数似乎是多余的,因为它将始终为1。
The solution I came up with is: 我想出的解决方案是:
SELECT X.A, COUNT(X.B)
FROM (
SELECT D.A, D.B
FROM MY_TABLE as D
GROUP BY D.A, D.B
) AS X
GROUP BY X.A
HAVING COUNT(X.B) = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.