将较旧的MySQL脚本转换为Postgres 9.5

时间:2016-06-05 20:24:11

标签: mysql sql postgresql

我有重复的示例数据(结果表):

year,teacher, score, class, state
2016, Jones, 80, math 102, NC
2016, Smith, 66, history, KY
2016, Jones, 40, math 101, SC
2014, Jones, 60, science, AK

我想创建一个新的汇总表(教师),其中包括老师订购的教师,平均成绩,年份和班级:

teacher, average, class, state
Jones, 60, 2016, math, NC SC

我原来的(较旧的)mysql脚本看起来类似于:

SELECT
  teacher, class,
  AVG(case when class rlike 'match' THEN score END) tlevel_avg,
GROUP_CONCAT(DISTINCT(state) order by state SEPARATOR ' ') 
FROM results
group by teacher
order by tlevel_avg desc
where year like '2012'   

将其导出到文件。

我尝试用postgres获得相同的结果,但我得到了每个人都有相同数据的独特教师(因为我创建了一个avg选择而没有教师价值的地方)

我不确定如何组织此查询以使avg与特定教师相关。

SELECT distinct teacher,
(select AVG( CASE when results.class SIMILAR TO '%math%' THEN results.score END) as training_level_avg from results)
(select AVG( CASE when results.class SIMILAR TO '%science%' THEN results.score END) as training_level_avg from results)
FROM RESULTS  
WHERE teacher NOT LIKE '%temporary%'  
AND results.year = '2011'
GROUP by results.teacher

主要是我试图通过给出一年的教师分组的所有课程的正确计算平均值来返回数据,但我还需要将此结果写入另一个“教师”表(奖金问题)。

非常感谢任何让我越过驼峰的帮助

1 个答案:

答案 0 :(得分:0)

您的查询会是这样的:

SELECT teacher, class,
       AVG(case when class = 'match' THEN score END) as tlevel_avg,
       STRING_AGG(DISTINCT state ORDER BY state, ' ') as states
FROM results
where year = '2012' 
GROUP BY judge
ORDER BY tlevel_avg DESC;

string_agg()相当于group_concat(),但语法略有不同。

我不记得上/下案件的处理方式是否存在差异。如果案件可能成为问题,您可以将= 'match'替换为ilike'匹配'。