我的数据库有三个表,
Studentdata with columns studentid , studentname
Assessmentdata with columns studentid, attemptedondate
Activitydata with columns studentid, date
每个表格行每天都会使用当前时间戳更新。
在识别方面需要帮助,Mostrecentdate列应该在比较这两个列的两个不同的表和两个不同的列之后得到日期。如果在activitydata和assessmentdata中列都为null,则在具有mostrecentdate的预期输出为null,如图所示。
左外连接应该是studentdata表,我应该在哪里写这个?
预期输出应为,
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
答案 0 :(得分:1)
尝试
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
或
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
示例输出:
| STUDENTID | STUDENTNAME | MOSTRECENTDATE | ------------------------------------------------- | 1 | abc | 2013-06-01 12:05:00 | | 2 | def | 2013-05-02 02:03:00 | | 3 | kjr | (null) |
这是 SQLFiddle 演示
答案 1 :(得分:0)
试试这个配偶:
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;