select machine_id, round(2*avg(if(activity_type ='start',-1,1)*timestamp),3) as processing_time from Activity groupby machine_id;
1280. 学生们参加各科测试的次数
笛卡尔积 cross join
1 2 3 4 5 6
select t.student_id, student_name, t.subject_name, count(e.subject_name) as attended_exams from (select*from Students crossjoin Subjects ) t leftjoin Examinations e on e.student_id = t.student_id and e.subject_name = t.subject_name groupby t.student_id, student_name, t.subject_name orderby t.student_id, t.subject_name;
570. 至少有5名直接下属的经理
聚合函数(如 count ())不能直接用在 where 子句中。 where 子句用于筛选原始行数据,而聚合函数是对分组后的数据进行计算,筛选分组结果需要用 having 子句。
1 2 3 4 5 6
select e1.name from Employee e1 join Employee e2 on e1.id = e2.managerId groupby e1.id havingcount(*) >=5;
ifnull(para,n):如果 para 是 null ,将 para 替换为 n 判断日期闭区间可用between… and…
1 2 3 4 5 6
select p.product_id, round(ifnull(sum(p.price * u.units) /sum(u.units), 0), 2) as average_price from Prices p leftjoin UnitsSold u on p.product_id = u.product_id and purchase_date between start_date and end_date groupby p.product_id;
1633. 各赛事的用户注册率
1 2 3 4
select contest_id, round(count(user_id)/(selectcount(*) from Users)*100, 2) as percentage from Register r groupby contest_id orderby percentage desc, contest_id;
select round(avg(if(order_date = customer_pref_delivery_date, 1, 0)) *100, 2) as immediate_percentage from Delivery where (customer_id, order_date) in (select customer_id, min(order_date) from Delivery groupby customer_id); #找出首次订单
550. 游戏玩法分析 IV
1 2 3 4 5 6 7 8
select round(avg(event_date isnot null), 2) as fraction from (select player_id, min(event_date) as first_login from Activity groupby player_id) fl #首次登录 leftjoin Activity a on fl.player_id = a.player_id and datediff(a.event_date, fl.first_login) =1;
619. 只出现一次的最大数字
1 2 3 4 5 6 7 8
select (select num from MyNumbers groupby num havingcount(num) =1 orderby num desc limit 1) as num;
1045. 买下所有产品的客户
1 2 3 4 5
select customer_id from customer groupby customer_id havingcount(distinct(product_key)) = (selectcount(product_key) from product);