简体   繁体   中英

Mysql Get data for Last Six weeks using JOIN

I have edited the query by selecting all the Employees data which have done assessments in past six weeks. Logically it should each employee two time if it has done assessments in two weeks but this query shows single record.

 select 
   AssessmentEmployee.
   EmployeeName,
   AVG(AssessmentListing.AssessmentScore),
   DATE_FORMAT((STR_TO_DATE(`AssessmentSubmittedDatetime`, '%d-%b-%Y %I:%i %p')) , '%Y-%m-%v') as _month 
 from AssessmentEmployee 
 LEFT JOIN AssessmentListing 
 ON  AssessmentEmployee.AssessmentID=AssessmentListing.AssessmentID 
 WHERE (STR_TO_DATE(`AssessmentSubmittedDatetime`, '%d-%b-%Y %I:%i %p') >= DATE_FORMAT(NOW() - INTERVAL 6 Week, '%Y' )) 
 group by AssessmentEmployee.EmployeeName 

I have following table which I am using.

AssessmentEmployee
 ID
 AssessmentID
 EmployeeName

Other table is AssessmentListing

ID
AssessmentID
AssessmentSubmittedDateTime
AssessmentScore

I want to get the employees who have score/ done assessments in Last sex weeks and their average score.

Sample of Data Column of AssessmentListing

ID  AssessmentID     AssessmentSubmittedDatetime     AssessmentScore 
1     040416024720     04-Apr-2016 02:48 PM             50

您正在做一个平均值,因此如果他们两次获得2分,则它将获得平均值。

Please try the following query:

select 
   AssessmentEmployee.
   EmployeeName,
   AVG(AssessmentListing.AssessmentScore),
   DATE_FORMAT((STR_TO_DATE(`AssessmentSubmittedDatetime`, '%d-%b-%Y %I:%i %p')) , '%Y-%v') as year_week
 from AssessmentEmployee 
 LEFT JOIN AssessmentListing 
 ON  AssessmentEmployee.AssessmentID=AssessmentListing.AssessmentID 
 WHERE UNIX_TIMESTAMP(DATE_FORMAT(STR_TO_DATE(`AssessmentSubmittedDatetime`,'%d-%b-%Y %I:%i %p'),'%Y-%m-%d')) >= UNIX_TIMESTAMP(CURDATE() - INTERVAL 6 WEEK)
 group by AssessmentEmployee.EmployeeName, year_week;

You shouldn't store date / time as string. Otherwise embrace these cumbersome jobs while processing them.

SELECT *, SUM(AssessmentScore) as total, SUM(AssessmentScore)/6 as avg
FROM `assessmentlisting` 
WHERE STR_TO_DATE(`AssessmentSubmittedDatetime`, '%d-%b-%Y %I:%i %p') > DATE_FORMAT(NOW() - INTERVAL 6 Week, '%Y-%m-%d %I:%i %p' ) 
GROUP BY assessmentlisting.AssessmentID

Hope it will works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM