My database has three tables,
Studentdata with columns studentid , studentname
Assessmentdata with columns studentid, attemptedondate
Activitydata with columns studentid, date
And each table row will be updated every day with the current timestamp.
Need help in identifying, Mostrecentdate column should get the date after comparing both these columns attemptedondate and date from two different tables and two different columns.if the column is null in both the activitydata and assessmentdata then print the student id with in the expected output with mostrecentdate is null as shown.
Left outer join should be with studentdata table , where should I write this ?
Expected output should be,
Studentid studentname mostrecentdate
1 abc 2013-06-01 12:05
2 def 2013-05-02 02:03
3 kjr null
My current query is:
select S.StudentId,
S.StudentAccountName,
CASE WHEN Max(D.attemptedondate) >= Max(A.date) THEN Max(D.attemptedondate)
ELSE Max(A.date) END
as MOSTRECENTDATE
from activitydata A
join Studentdata S on A.StudentId=s.StudentID
join Assessmentdata D on S. StudentID =D. StudentID
group by S.StudentId,
S.StudentAccountName
Try
SELECT s.studentid, s.studentname,
NULLIF(GREATEST(COALESCE(a.max_date, 0),
COALESCE(b.max_date, 0)), 0) mostrecentdate
FROM Studentdata s LEFT JOIN
(
SELECT studentid, MAX(attemptedondate) max_date
FROM Assessmentdata
GROUP BY studentid
) a ON s.studentid = a.studentid LEFT JOIN
(
SELECT studentid, MAX(date) max_date
FROM Activitydata
GROUP BY studentid
) b ON s.studentid = b.studentid
or
SELECT s.studentid, s.studentname, mostrecentdate
FROM Studentdata s LEFT JOIN
(
SELECT studentid, MAX(max_date) mostrecentdate
FROM
(
SELECT studentid, MAX(attemptedondate) max_date
FROM Assessmentdata
GROUP BY studentid
UNION ALL
SELECT studentid, MAX(date) max_date
FROM Activitydata
GROUP BY studentid
) a
GROUP BY studentid
) b ON s.studentid = b.studentid
Sample output:
| STUDENTID | STUDENTNAME | MOSTRECENTDATE | ------------------------------------------------- | 1 | abc | 2013-06-01 12:05:00 | | 2 | def | 2013-05-02 02:03:00 | | 3 | kjr | (null) |
Here is SQLFiddle demo
Try this one mate:
SELECT SD.StudentID
, SD.StudentName
, CASE
WHEN MAX(IFNULL(SS.attemptedondate, '')) >= MAX(IFNULL(AC.date, '')) THEN MAX(SS.attemptedondate)
WHEN MAX(IFNULL(SS.attemptedondate, '')) < MAX(IFNULL(AC.date, '')) THEN MAX(AC.date)
ELSE NULL
END AS MOSTRECENTDATE
FROM Studentdata SD
LEFT JOIN Assessmentdata SS ON SS.StudentID = SD.StudentID
LEFT JOIN Activitydata AC ON AC.StudentID = SD.StudentID
GROUP BY SD.StudentID;
Here is the SQLFiddle Demo .
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.