08 学生课程分数的Spark SQL分析
生成表头
from pyspark.sql.types import *
from pyspark.sql import Row
schemaString="name course score"
fields=[StructField(field_name,StringType(),True) for field_name in schemaString.split(" ")]
bt=StructType(fields)
bt
生成数据
xssj=spark.sparkContext.textFile("file:///usr/local/spark/mycode/rdd/xs.txt").map(lambda line:line.split(',')).map(lambda x:Row(name=x[0],course=x[1],score=int(x[2])))
xssj.take(3)
拼接
xsb=spark.createDataFrame(xssj,bt)
xsb.show()
用DataFrame的操作或SQL语句完成以下数据分析要求,并和用RDD操作的实现进行对比:
- 每个分数+5分。
- xsb.select('name','course',xsb.score+5).show()
- 总共有多少学生?
- xsb.select('name').distinct().count()
- 总共开设了哪些课程?
- xsb.select('course').distinct().show()
- 每个学生选修了多少门课?
- xsb.groupBy('name').count().show()
-
- 每门课程有多少个学生选?
- xsb.groupBy('course').count().show()
- 每门课程大于95分的学生人数?
- xsb.filter(xsb.score>95).groupBy('course').count().show()
- Tom选修了几门课?每门课多少分?
- xsb.filter(xsb.name=='Tom').show()
- Tom的成绩按分数大小排序。
- xsb.filter(xsb.name=='Tom').orderBy(xsb.score).show()
- Tom的平均分。
- xsb.filter(xsb.name=='Tom').agg({'score':'mean'}).show()
- 求每门课的平均分,最高分,最低分。
-
xsb.filter(xsb.name=='Tom').groupBy('course').agg({'score':'mean'}).show()
- xsb.filter(xsb.name=='Tom').groupBy('course').agg({'score':'max'}).show()
- xsb.filter(xsb.name=='Tom').groupBy('course').agg({'score':'min'}).show()
- 二、用SQL语句完成以上数据分析要求
- xsb.createOrReplaceTempView('xsb')
- 每个分数+5分。
- spark.sql('SELECT course,name,score+5 as score From xsb').show()
-
- 总共有多少学生?
- spark.sql('SELECT count(distinct name) From xsb').show()
-
- 总共开设了哪些课程?
- spark.sql('SELECT distinct course FROM xsb').show()
-
- 每个学生选修了多少门课?
- spark.sql('SELECT name,count(course) FROM xsb group by name').show()
-
- 每门课程有多少个学生选?
- spark.sql('SELECT course,count(name) FROM xsb group by course').show()
-
- 每门课程大于95分的学生人数?
- spark.sql('SELECT course,count(name) FROM xsb where score>95 group by course').show()
-
- Tom选修了几门课?每门课多少分?
- spark.sql('SELECT name,course,score FROM xsb where name="Tom"').show()
-
- Tom的成绩按分数大小排序。
- spark.sql('SELECT name,course,score FROM xsb where name="Tom" order by score desc').show()
-
- Tom的平均分。
- spark.sql('SELECT round(avg(score),2) FROM xsb where name="Tom"').show()
-
- 求每门课的平均分,
- spark.sql('SELECT course,round(avg(score),2) FROM xsb group by course').show()
-
- 最高分,
- spark.sql('SELECT course,max(score) FROM xsb group by course').show()
-
- 最低分。
- spark.sql('SELECT course,min(score) FROM xsb group by course').show()
-
- 求每门课的选修人数及平均分,精确到2位小数。
- spark.sql('SELECT course,count(name),round(avg(score),2) as avg FROM xsb group by course').show()
-
- 每门课的不及格人数,通过率
- spark.sql('SELECT course,count(name) as n FROM xsb group by course').createOrReplaceTempView('a')
- spark.sql('SELECT course,count(score) as bjg FROM xsb where score<60 group by course').createOrReplaceTempView('b')
- c=spark.sql('SELECT a.course,b.bjg,round(1-(a.n-b.bjg)/a.n,2) as tgl FROM a left join b on a.course=b.course')
- c.show()
-