SQL練習00015
需求:查詢活躍業務
事件表:Events
Column Nam | Type |
---|---|
business_id | int |
event_type | varchar |
occurences | int |
此表的主鍵是 (business_id, event_type)。
表中的每一行記錄了某種型別的事件在某些業務中多次發生的資訊。
寫一段 SQL 來查詢所有活躍的業務。
如果一個業務的某個事件型別的發生次數大於此事件型別在所有業務中的平均發生次數,並且該業務至少有兩個這樣的事件型別,那麼該業務就可被看做是活躍業務。
查詢結果格式如下所示:
Events table:
business_id | event_type | occurences |
---|---|---|
1 | reviews | 7 |
3 | reviews | 3 |
1 | int | 11 |
2 | ads | 7 |
3 | ads | 6 |
1 | page views | 3 |
2 | page views | 12 |
result table:
business_id |
---|
1 |
‘reviews’、 ‘ads’ 和 ‘page views’ 的總平均發生次數分別是 (7+3)/2=5, (11+7+6)/3=8, (3+12)/2=7.5。
id 為 1 的業務有 7 個 ‘reviews’ 事件(大於 5)和 11 個 ‘ads’ 事件(大於 8),所以它是活躍業務。
--建表語句
Create table If Not Exists Events (business_id int, event_type varchar(10), occurences int);
Truncate table Events;
insert into Events (business_id, event_type, occurences) values ('1', 'reviews', '7');
insert into Events (business_id, event_type, occurences) values ('3', 'reviews', '3');
insert into Events (business_id, event_type, occurences) values ('1', 'ads', '11');
insert into Events (business_id, event_type, occurences) values ('2', 'ads', '7');
insert into Events (business_id, event_type, occurences) values ('3', 'ads', '6');
insert into Events (business_id, event_type, occurences) values ('1', 'page views', '3');
insert into Events (business_id, event_type, occurences) values ('2', 'page views', '12');
--答案1
with tmp as
(
select
event_type,
avg(occurences) as mk
from
Events group by event_type
)
select
business_id
from
Events e join
tmp on
e.event_type=tmp.event_type where
occurences>mk group by
business_id having
count(1)>=2
--答案2
select
business_id
from
(
select
*,
if(occurences>avg(occurences) over(partition by event_type),1,0) as mk
from
Events
)
a group by
business_id having
sum(mk)>1
相關文章
- SQL練習題SQL
- SQL練習00012SQL
- sql查詢入門練習題SQL
- 牛客SQL練習第21題SQL
- Day5-SQL綜合練習(Datawhale)SQL
- [MySQL光速入門]008 SQL強化練習MySql
- [MySQL光速入門]009 SQL強化練習答案MySql
- 簡單練習Microsoft SQL Server MERGE同步兩個表ROSSQLServer
- markdown 使用練習練習
- SQL經典練習題48道之一(1-10)SQL
- SQL經典練習題48道之二(11-19)SQL
- SQL經典練習題48道之三(20-25)SQL
- SQL經典練習題48道之四(26-30)SQL
- SQL經典練習題48道之五(31-35)SQL
- SQL經典練習題48道之六(36-40)SQL
- SQL經典練習題48道之七(41-48)SQL
- 【躍遷之路】SQL語句刻意練習(最後更新:2018.06.25)SQL
- Hive SQL必刷練習題:同時線上人數問題(*****)HiveSQL
- 新手練習:Python練習題目Python
- MYSQL練習1: DQL查詢練習MySql
- 招聘要求裡的「熟練使用 SQL」 你熟練麼?SQL
- [資料庫]50道經典SQL練習題,使用MySQL5.7解答資料庫MySql
- MySQL基礎練習20題,看看你的sql基礎man不manMySql
- python練習Python
- MySQL練習MySql
- ddl練習
- latex練習
- MySQ練習
- openGauss練習
- U7-11課綜合練習+12課階段測評練習——複習練習題目
- SQL學習SQL
- SQL 學習SQL
- SQL複習SQL
- python 練習0000Python
- C++練習C++
- shell練習題
- 【練習】canvas——flappyBirdCanvasAPP
- Python 練習題Python