- 计算每天的注册用户,购买人数和当天购买人数
第一种 相关子查询
select u_date,count(distinct u_id) as '注册人数',(select count(distinct u2.u_id) as '购买人数'from user_table u2 join order_table o on u2.u_id=o.u_idwhere u1.u_date=u2.u_date #相关子查询group by u2.u_date),(select count(distinct u3.u_id) as '当天购买人数'from user_table u3 join order_table o on u3.u_id=o.u_id and u3.u_date=o.o_datewhere u1.u_date=u3.u_date #相关子查询group by u3.u_date)from user_table u1group by u1.u_dateorder by u1.u_date;
第二种 三表连接
select t1.u_date,'注册人数','购买人数','当天购买人数'from(select u_date,count(distinct u_id) as '注册人数'from user_table u1group by u_date) as t1join (select u2.u_date,count(distinct u2.u_id) as '购买人数'from user_table u2 join order_table o on u2.u_id=o.u_idgroup by u2.u_date) as t2 on t1.u_date=t2.u_datejoin (select u3.u_date,count(distinct u3.u_id) as '当天购买人数'from user_table u3 join order_table o on u3.u_id=o.u_id and u3.u_date=o.o_dategroup by u3.u_date) as t3 on t1.u_date=t3.u_dateorder by t1.u_date;
2.牛客每次考试完,都会有一个成绩表(grade),如下:
请你写一个sql语句查询用户分数大于其所在工作(job)分数的平均分的所有grade的属性,并且以id的升序排序
#用户分数大于其所在工作(job)分数的平均分的所有gradeselect *from grade g1where score > (select avg(score)from grade g2where g1.job=g2.job #相关子查询group by job)order by id;
