1

我的数据库有三个表,

Studentdata with columns studentid , studentname
Assessmentdata with columns studentid, attemptedondate
Activitydata with columns studentid, date

并且每个表格行每天都会使用当前时间戳进行更新。

在识别方面需要帮助,Mostrecentdate 列应该在比较两个不同表和两个不同列中的这两个列尝试过的日期和日期之后获取日期。如果该列在活动数据和评估数据中为空,则在预期输出中打印学生 ID mostrecentdate 为空,如图所示。

左外连接应该是学生数据表,我应该在哪里写这个?

预期输出应该是,

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
4

2 回答 2

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

样本输出:

| 学生证 | 学生姓名 | 最近日期 |
-------------------------------------------------
| 1 | 美国广播公司 | 2013-06-01 12:05:00 |
| 2 | 定义 | 2013-05-02 02:03:00 |
| 3 | kjr | (空) |

这是SQLFiddle演示

于 2013-06-24T09:08:53.983 回答
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;

这是SQLFiddle 演示

于 2013-06-24T09:47:19.327 回答