LeetCode 1126. Active Businesses SQL Solution
Problem
LeetCode SQL Problem
- Active Businesses
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 |
Solution - Group By and CTEs
- MySQL
- TSQL
Active Businesses
WITH AvgEventOccurences
AS (
SELECT event_type
-- Calculate the average occurences of each event type among all businesses
,avg(cast(occurences AS FLOAT)) AS avg_occurences
FROM Events
GROUP BY event_type
)
SELECT E.business_id
FROM Events AS E
INNER JOIN AvgEventOccurences AS AG ON E.event_type = AG.event_type
-- Occurrences of current event type is greater than the average occurences of this event type among all businesses.
WHERE E.occurences > AG.avg_occurences
GROUP BY E.business_id
-- If a business has more than 1 event type that matches the criteria, it's considered Active
HAVING count(DISTINCT E.event_type) > 1
Active Businesses
WITH AvgEventOccurences
AS (
SELECT event_type
-- Calculate the average occurences of each event type among all businesses
,avg(cast(occurences AS FLOAT)) AS avg_occurences
FROM Events
GROUP BY event_type
)
SELECT E.business_id
FROM Events AS E
INNER JOIN AvgEventOccurences AS AG ON E.event_type = AG.event_type
-- Occurrences of current event type is greater than the average occurences of this event type among all businesses.
WHERE E.occurences > AG.avg_occurences
GROUP BY E.business_id
-- If a business has more than 1 event type that matches the criteria, it's considered Active
HAVING count(DISTINCT E.event_type) > 1
Solution - AVG() Window Function
- MySQL
- TSQL
Active Businesses
WITH EventsAnalysis
AS (
SELECT *
-- Calculate the average occurences of this row's event type among all businesses
,avg(cast(occurences AS FLOAT)) OVER (PARTITION BY event_type) AS avg_occurences
FROM Events
)
SELECT business_id
FROM EventsAnalysis
-- Occurrences of current event type is greater than the average occurences of this event type among all businesses.
WHERE occurences > avg_occurences
GROUP BY business_id
-- If a business has more than 1 event type that matches the criteria, it's considered Active
HAVING count(DISTINCT event_type) > 1
Active Businesses
WITH EventsAnalysis
AS (
SELECT *
-- Calculate the average occurences of this row's event type among all businesses
,avg(cast(occurences AS FLOAT)) OVER (PARTITION BY event_type) AS avg_occurences
FROM Events
)
SELECT business_id
FROM EventsAnalysis
-- Occurrences of current event type is greater than the average occurences of this event type among all businesses.
WHERE occurences > avg_occurences
GROUP BY business_id
-- If a business has more than 1 event type that matches the criteria, it's considered Active
HAVING count(DISTINCT event_type) > 1
Query Output
business_id |
---|
1 |