+---------------+---------+
|Column Name |Type|+---------------+---------+
| business_id | int || event_type | varchar || occurrences | int |+---------------+---------+
(business_id, event_type) is the primarykey (combination of columns withuniquevalues) of this table.
Eachrowin the table logs the info that an event ofsometype occurred atsome business for a number of times.
The average activity for a particular event_type is the average occurrences across all companies that have this event.
An active business is a business that has more than oneevent_type such that their occurrences is strictly greater than the average activity for that event.
Events table:
+-------------+------------+-------------+
| business_id | event_type | occurrences |+-------------+------------+-------------+
|1| reviews |7||3| reviews |3||1| ads |11||2| ads |7||3| ads |6||1| page views |3||2| page views |12|+-------------+------------+-------------+
Output:
+-------------+
| business_id |+-------------+
|1|+-------------+
Explanation:
The average activity foreach event can be calculated as follows:
-'reviews': (7+3)/2=5-'ads': (11+7+6)/3=8-'page views': (3+12)/2=7.5The business with id=1 has 7'reviews' events (morethan5) and11'ads' events (morethan8), so it is an active business.
The key idea is to first compute the average occurrences for each event type, then compare each business’s occurrences for each event type to this average. A business is “active” if it exceeds the average for more than one event type.
WITH AvgEvents AS (
SELECT event_type, AVG(occurrences) AS avg_occurrences
FROM Events
GROUPBY event_type
),
AboveAvg AS (
SELECT e.business_id, e.event_type
FROM Events e
JOIN AvgEvents a
ON e.event_type = a.event_type
WHERE e.occurrences > a.avg_occurrences
)
SELECT business_id
FROM AboveAvg
GROUPBY business_id
HAVINGCOUNT(DISTINCT event_type) >1;