SQL - Return 分区中的较大者

SQL - Return The Greater of a Partition

我有以下 table -

我的目标是 return Company/ID 具有最高“计数”的行,对应于 ID 完成的分区。

因此 预期输出 应该如下所示:

我当前的代码 returns 是在 所有 ids 上分区的计数。我只想 return 计数最高的那个。

当前代码-

select distinct Company, Id, count(*) over (partition by ID)
from table1
where company in ("Facebook","Apple")

我的输出:

我们可以在这里使用 ROW_NUMBER 和聚合查询:

WITH cte AS (
    SELECT Company, ID, COUNT(*) AS Count,
           ROW_NUMBER() OVER (PARTITION BY Company ORDER BY COUNT(*) DESC) rn
    FROM table1
    GROUP BY Company, ID
)

SELECT Company, ID, Count
FROM cte
WHERE rn = 1;

这里是 运行 demo MySQL。

SELECT company, id, COUNT(*)
  FROM table1
 GROUP BY EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO
HAVING COUNT(*) > 1;

您的基本查询不正确。无论公司如何,您都按 ID 进行分区,但在您的请求评论中,您明确表示要按 ID 和公司进行计数。这必须是

select distinct company, id, count(*) over (partition by company, id)
from table1
where company in ('Facebook','Apple');

但该查询归结为纯粹的聚合,根本不需要 window 函数。它正在评估每一行的计数,只是稍后用 DISTINCT 消除重复项。 DISTINCT 是一项成本高昂的操作,那么为什么不首先简单地聚合您的行呢?

select company, id, count(*)
from table1
where company in ('Facebook','Apple')
group by company, id;

现在您只想保留每个公司计数最高的行,这就是 window 函数发挥作用的地方:

select  company, id, total
from
(
  select
    company,
    id,
    count(*) as total,
    max(count(*)) over (partition by company) as max_total
  from table1
  where company in ('Facebook','Apple')
  group by company, id
) aggregated
where total = max_total;