Active Business Problem
#1126
Description
LeetCode Problem 1126.
Table: Events
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| business_id | int |
| event_type | varchar |
| occurences | int |
+---------------+---------+
(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 query result format is in the following example:
Events table:
+-------------+------------+------------+
| business_id | event_type | occurences |
+-------------+------------+------------+
| 1 | reviews | 7 |
| 3 | reviews | 3 |
| 1 | ads | 11 |
| 2 | ads | 7 |
| 3 | ads | 6 |
| 1 | page views | 3 |
| 2 | page views | 12 |
+-------------+------------+------------+
Result table:
+-------------+
| business_id |
+-------------+
| 1 |
+-------------+
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.
Solution
Approach: Window Average per Event Type
- Average of each event type.
AVG(occurences) OVER (PARTITION BY event_type)puts the average of that event type, over all businesses that have it, on every row, without collapsing the rows the wayGROUP BYwould. - Above average. Keep the rows where
occurences > type_average. The comparison is strict: a value equal to the average does not count. - More than one. Group the remaining rows by
business_idand keep the businesses withCOUNT(*) > 1. Each row is a different event type, since(business_id, event_type)is the primary key.
In the example, the averages are 5 for reviews, 8 for ads and 7.5 for page views. Business 1 is above average for reviews (7) and ads (11), so it is active; business 2 is above average only for page views.
The Pandas version gets the same per-type average with groupby("event_type").transform("mean"), filters, and counts rows per business.
WITH with_average AS (
SELECT business_id,
occurences,
AVG(occurences) OVER (PARTITION BY event_type) AS type_average
FROM Events
)
SELECT business_id
FROM with_average
WHERE occurences > type_average
GROUP BY business_id
HAVING COUNT(*) > 1;