检索行数大于1的分组计数的方法是:

huangapple go评论55阅读模式
英文:

How to retrieve rows with group count > 1

问题

我想检索所有行,其中一个组的计数> 1,不使用子查询。如果使用子查询,它将是

SELECT *
FROM abc
LEFT JOIN
(SELECT a, COUNT() AS cnt
FROM abc
GROUP BY a
HAVING COUNT(
) > 1) aa
ON abc.a = aa.a
WHERE aa.a IS NOT NULL

这是表格:

a b
1 2
1 3
2 3
2 4
3 3
4 4

结果将是

a b
1 2
1 3
2 3
2 4
英文:

I want to retrieve all the rows which the count of a group > 1 without subquery. If subquery used, it will be

SELECT *
FROM abc
LEFT JOIN 
    (SELECT a, COUNT(*) AS cnt
     FROM abc
     GROUP BY a
     HAVING COUNT(*) > 1) aa 
ON abc.a = aa.a
WHERE aa.a IS NOT NULL

Here is the table:

|a|b|
|-|-|
|1|2|
|1|3|
|2|3|
|2|4|
|3|3|
|4|4|

The result would be

|a|b|
|-|-|
|1|2|
|1|3|
|2|3|
|2|4|

答案1

得分: 2

一个我经常在这种情况下使用的方法是自连接。大致如下:

SELECT a.*
FROM abc a
INNER JOIN abc b ON a.a = b.a
WHERE a.b <> b.b;

它的优点是非常易读,通常比具有子查询的查询要快得多。

英文:

An approach that I often use in such cases is a self join. Something along these lines:

SELECT a.*
FROM abc a
INNER JOIN abc b ON a.a = b.a
WHERE a.b &lt;&gt; b.b;

It has the advantage of being eminently readable, and usually considerably quicker to type than a query with sub-query.

答案2

得分: 2

只使用窗口函数!

选择 a, b
从 (
    选择 t.*, count(*) over(partition by a) cnt
    从 abc t
) t
其中 cnt > 1

窗口计数根据 a 对数据集进行分区,然后计算当前分区中的记录总数。然后,我们可以使用这些信息来筛选数据集。

英文:

Just use window functions!

select a, b
from (
    select t.*, count(*) over(partition by a) cnt
    from abc t
) t
where cnt &gt; 1

The window count partitions the dataset by a, then counts the overall number of records in the current partition. We can then use this information to filter the dataset.

huangapple
  • 本文由 发表于 2023年5月25日 12:11:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定