views:

193

answers:

4

Hi,

I have a model like:

Question - Id - CreatedOn

Answer - Id - CreatedOn - QuestionID

No I want to get the first question with the newest answer.

I am using SQL Server 2005.

Thanks, Chris

A: 

Something like this:

SELECT TOP 1 Question FROM Questions JOIN Answers ON Questions.Id=Answers.QuestionID ORDER BY Answers.CreatedOn DESC;

Jesse Weigert
Not SQL Server syntax
gbn
A: 
select top 1 Question from questions
  inner join answers on questions.Id = answers.QuestionId
order by answers.CreatedOn desc

Sorry for the delay in replying to the comment, I didn't have time earlier to test it out:

This gets more complicated, but something like this should work:

select top 5 Question from questions
  inner join answers on questions.Id = answers.QuestionId
GROUP BY Question
ORDER BY max(answers.CreatedOn) desc

This seems to be the standard pattern to effectively get a distinct set of data from a table without including the order by column in the record set.

Be aware that the number of elements you want to select (in this case 5) has to be a constant in SQL. If you have the advantage of using something like LINQ to SQL, you could write this in LINQ and have the take amount as a variable.

So, in response to the latest comment, you'd just add max(answers.CreatedOn) to the select statement:

select top 5 Question, max(answers.CreatedOn)
from questions
  inner join answers on questions.Id = answers.QuestionId
GROUP BY Question
ORDER BY max(answers.CreatedOn) desc
Zhaph - Ben Duguid
Hi, If I want to get the Top 5 I have duplicates. Could you tell me how to create the query for distinct top 5 questions?
Christian
Sounds good. Just one last question. I want to get the date of lates answer from the answers table in the query, too. So QuestionId and its related alias "LastAnswerDate" in one query.
Christian
+1  A: 
Select top 1 *
from questions, answers
where question.id = answers.questionid
order by answers.createdon desc
Ash M
A: 

I would try something like this

SELECT Id, CreatedOn    
FROM Question Q    
WHERE Q.id IN    
(SELECT DISTINCT TOP 5 A.QuestionID FROM Answer A ORDER BY A.CreatedOn)
Jhonny D. Cano -Leftware-
I have a problem: A.CreatedOn is not accepted because it is not in the select part of the subquery, any tip?
Christian
What if you try this?SELECT DISTINCT Id, CreatedOn FROM Question AS QWHERE Q.id IN(SELECT TOP 5 A.QuestionID FROM Answer A WHERE A.QuestionId = Q.id ORDER BY A.CreatedOn)The SQL does not permit to make distinct query among with order by
Jhonny D. Cano -Leftware-