INSERT INTO FinishwordsStat ( uid, unitId, content, wordsCount, completeCount, created, howmuch, maxScore, avgScore , areaid ) Values ( #{uid}, #{unitId}, #{content}, #{wordsCount}, #{completeCount},current_timestamp, #{howmuch}, #{maxScore}, #{avgScore} , #{areaid} ) UPDATE UnivFinishwordsStat SET uid = #{uid}, unitId = #{unitId}, content = #{content}, wordsCount = #{wordsCount}, completeCount = #{completeCount}, created = #{created}, howmuch = #{howmuch}, maxScore = #{maxScore}, avgScore = #{avgScore} , areaid= #{areaid} where uid=#{uid} and unitId=#{unitId} and areaid = #{areaid} with temp as ( select distinct a.uid , b.lessonId as unitId , a.areaId from ( select uid , wordsId , areaId from UnivWordAchive where created > current_date - interval '1 day' and created < current_date ) as a inner join words b on a.wordsId = b.wordsId ) DELETE FROM UnivFinishwordsStat m USING temp WHERE m.uid = temp.uid and m.unitId = temp.UnitId with temp as ( select distinct a.uid , b.lessonId as unitId , a.areaId from ( select uid , wordsId , areaId from UnivWordAchive where created > current_date - interval '1 day' and created < current_date ) as a inner join words b on a.wordsId = b.wordsId ) insert into UnivFinishWordsStat ( uid , unitid , content , wordscount , completecount , created , howmuch , maxscore , avgscore , areaid ) select p.uid , p.unitId , s.lessonname as content , r.wordsCount , p.completeCount , current_timestamp , howmuch , maxScore , avgScore , areaid from ( select temp.uid , temp.unitId , temp.areaid , count( distinct a.wordsId ) as completecount, count(a.wordachiveid) as howmuch , max(a.score ) as maxscore , round(avg(a.score)) as avgscore from temp inner join words b on temp.unitId = b.lessonId inner join UnivWordAchive a on temp.uid = a.uid and b.wordsId = a.wordsId group by temp.uid , temp.unitId , temp.areaId ) as p inner join ( select lessonId as unitId , count(*) as wordsCount from Words group by lessonId ) as r on p.unitId = r.unitid inner join Lesson s on p.unitId = s.lessonId