Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to fetch the data whose latest datetime who status 1.

Name | Teststatus | ExamDate | Subject
Johan | 0 | 2019-01-01 25:46 | Maths
Johan | 1 | 2019-01-01 25:48 | Maths
Johan | 0 | 2019-01-01 25:47 | Maths
Ram | 0 | 2019-01-01 25:13 | Maths
Ram | 0 | 2019-01-01 25:45 | Maths
Ram | 1 | 2019-01-01 25:42 | Maths

What I have tried:

select Et.Name, Et.Status, Max(Et.ExamDate)
from Exam Et join Subject S on Et.Code =S.code
group by Et,Name,Et.Status


Name | Teststatus | ExamDate
Johan | 1 | 2019-01-01 25:48
Ram | 0 | 2019-01-01 25:45
Ram | 1 | 2019-01-01 25:42
Johan | 0 | 2019-01-01 25:47

But i need to get latest datetime and who has passed in exam

Name | Teststatus | ExamDate
Johan | 1 | 2019-01-01 25:48
Posted
Updated 4-May-19 21:14pm

GROUP BY doesn't do what you want - particularly not like that. Have a look here: SQL GROUP By and the "Column 'name' is invalid in the select list because..." error[^] which explains what it does do!

You need to think about your data and what you want to retrieve:
"Passed test"
and
"Latest date"
So do that:
SQL
SELECT TOP 1 Name, TestStatus, ExamDate FROM Exam
WHERE TestStatus = 1
ORDER BY ExamDate DESC
TOP 1 says "return only the first value", the WHERE restricts it to passed tests, and the ORDER BY controls the order in which rows are returned.
 
Share this answer
 
v3
Comments
[no name] 5-May-19 7:12am    
Should this not be "TOP(1)" instead of "TOP ONE"?
OriginalGriff 5-May-19 7:18am    
Yes - fixed.
Oops ... I needed more coffee, obviously ... good spot! :thumbsup:
SQL
with co
(
Select code, max(examdate) as examdate from exam group by code
)
select et.name, et.status, c.examdate
join co c on et.code = c.code


Why did you join on subject if you don't select from it?

you can also join to another table to pull if they passed, but you didn't show me how
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900