Active Businesses LeetCode Solution

Last updated on March 10th, 2025 at 10:52 pm

Here, we see the Active Businesses LeetCode Solution. This Leetcode problem is solved using MySQL and Pandas.

List of all LeetCode Solution

Level of Question

Medium

Active Businesses LeetCode Solution

Active Businesses LeetCode Solution

1. Problem Statement

Column NameType
business_idint
event_typevarchar
occurencesint
Table: Events

(business_id, event_type) is the primary key of this table.
Each row in the table logs the info that an event of some type occured at some business for a number of times.

Write an SQL query to find all active businesses. An active business is a business that has more than one event type with occurences greater than the average occurences of that event type among all businesses.

The result format is in the following example.

Example 1:
Input:

business_idevent_typeoccurences
1reviews7
3reviews3
1ads11
2ads7
3ads6
1page views3
2page views12
Events table:

Output:

business_id
1

Explanation:
Average for ‘reviews’, ‘ads’ and ‘page views’ are (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5 respectively.
Business with id 1 has 7 ‘reviews’ events (more than 5) and 11 ‘ads’ events (more than 8) so it is an active business.

2. Code Implementation in Different Languages

2.1 Active Businesses MySQL

select 
  business_id 
from 
  Events e, 
  (
    select 
      event_type, 
      avg(occurences) as avg_occurences 
    from 
      Events 
    group by 
      event_type
  ) as a 
where 
  e.event_type = a.event_type 
  and e.occurences > a.avg_occurences 
group by 
  e.business_id 
having 
  count(*) > 1;
Scroll to Top