1. 计算每天的注册用户,购买人数和当天购买人数

    第一种 相关子查询

    1. select u_date,count(distinct u_id) as '注册人数'
    2. ,(
    3. select count(distinct u2.u_id) as '购买人数'
    4. from user_table u2 join order_table o on u2.u_id=o.u_id
    5. where u1.u_date=u2.u_date #相关子查询
    6. group by u2.u_date
    7. )
    8. ,(
    9. select count(distinct u3.u_id) as '当天购买人数'
    10. from user_table u3 join order_table o on u3.u_id=o.u_id and u3.u_date=o.o_date
    11. where u1.u_date=u3.u_date #相关子查询
    12. group by u3.u_date
    13. )
    14. from user_table u1
    15. group by u1.u_date
    16. order by u1.u_date;

    第二种 三表连接

    1. select t1.u_date,'注册人数','购买人数','当天购买人数'
    2. from(
    3. select u_date,count(distinct u_id) as '注册人数'
    4. from user_table u1
    5. group by u_date
    6. ) as t1
    7. join (
    8. select u2.u_date,count(distinct u2.u_id) as '购买人数'
    9. from user_table u2 join order_table o on u2.u_id=o.u_id
    10. group by u2.u_date
    11. ) as t2 on t1.u_date=t2.u_date
    12. join (
    13. select u3.u_date,count(distinct u3.u_id) as '当天购买人数'
    14. from user_table u3 join order_table o on u3.u_id=o.u_id and u3.u_date=o.o_date
    15. group by u3.u_date
    16. ) as t3 on t1.u_date=t3.u_date
    17. order by t1.u_date;

    2.牛客每次考试完,都会有一个成绩表(grade),如下:
    image.png
    请你写一个sql语句查询用户分数大于其所在工作(job)分数的平均分的所有grade的属性,并且以id的升序排序

    1. #用户分数大于其所在工作(job)分数的平均分的所有grade
    2. select *
    3. from grade g1
    4. where score > (
    5. select avg(score)
    6. from grade g2
    7. where g1.job=g2.job #相关子查询
    8. group by job
    9. )
    10. order by id;