2

我有一个无法更改的查询。例如:

SELECT studentid FROM school s LEFT OUTER JOIN mall m ON s.studentid=m.studentid

一个学生在表 Mall 中有两行。上面的查询输出重复,因为学生在表 mall 上有两行 id 相同的行。表 mall 上有一个日期列,我只想选择日期最新的学生。我该怎么做?(只需在 where 子句中添加条件)

4

5 回答 5

1
SELECT studentid 
FROM school s 
LEFT OUTER JOIN mall m 
ON s.studentid=m.studentid
ORDER BY date DESC
GROUP BY studentid
于 2012-10-09T07:46:55.520 回答
1
where m.date=(select max(date) from mall where studentid=m.studentid)
于 2012-10-09T07:43:07.847 回答
1

尝试这个:

select s.studentid 
from school s 
INNER JOIN malls m1 ON m1.studentid = s.studentid
INNER JOIN
(
   SELECT studentid, Max(DateField) MaxDate 
   FROM mall
   GROUP BY studentid
) m2 on m1.studentid = m2.studentid AND m1.DateField = m2.MaxDate 
于 2012-10-09T07:43:45.507 回答
0

您可以使用 order by 和 limit ,如下所示:

select studentid 
from school s 
left outer join mall m on s.studentid=m.studentid 
order by date desc 
limit 1

它比在 where 子句上使用多个选择查询更简单。

于 2012-10-09T07:43:26.130 回答
0

如果您正在使用SQL Server

WITH LatestRecord
AS
(
    SELECT  studentID, date,
            ROW_NUMBER() OVER(Partition BY StudentID Order By DATE DESC) AS RN
    FROM    mall
)
SELECT  a.*, b.studentID, b.date
FROM    School a
        INNER JOIN LatestRecord b
            on a.StudentID = b.Student_ID
WHERE   RN = 1
于 2012-10-09T07:44:37.643 回答