我有一个无法更改的查询。例如:
SELECT studentid FROM school s LEFT OUTER JOIN mall m ON s.studentid=m.studentid
学生在购物中心有两排。上面的查询输出重复项,因为学生在表商城上有两行具有相同ID的行。表商城上有一个日期列,我只想选择具有最新日期的学生。我该怎么办?(只是在where子句中添加条件)
答案 0 :(得分:1)
where m.date=(select max(date) from mall where studentid=m.studentid)
答案 1 :(得分: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
答案 2 :(得分:1)
SELECT studentid
FROM school s
LEFT OUTER JOIN mall m
ON s.studentid=m.studentid
ORDER BY date DESC
GROUP BY studentid
答案 3 :(得分: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子句上使用多个select查询更简单。
答案 4 :(得分: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