Your base query is incorrect. You partition by ID regardless of the company, but in your request comments you clarify that you want to count per ID and company. This would have to be
select distinct company, id, count(*) over (partition by company, id)
from table1
where company in ('Facebook','Apple');
But that query boils down to be a mere aggregation and doesn't need window functions at all. It is evaluating the count for each single row, only to dismiss duplicates later with DISTINCT
. DISTINCT
is a costly operation, so why not simply aggregate your rows in the first place?
select company, id, count(*)
from table1
where company in ('Facebook','Apple')
group by company, id;
Now you only want to keep the rows with the highest count per company, and this is where window functions come into play:
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;