好的,所以说我有两张桌子。
问题
回答
并说我想创建一个查询,返回问题和最新创建的答案,如这些列
QuestionID QuestionName AnswerDescription CreatedDate
这可能吗?
我可以进行查询以获取问题和答案的所有组合
SELECT q.QuestionID, q.QuestionName, a.AnswerDescription, a.CreatedDate FROM QUESTION q
INNER JOIN ANSWER a
ON q.questionID = a.QuestionID
但有没有办法我可以做这样的事情,但是它只返回最新答案而不是全部答案?
答案 0 :(得分:4)
SELECT q.QuestionID,
q.QuestionName,
a.AnswerDescription,
a.CreatedDate
FROM QUESTION AS q
INNER JOIN (SELECT QuestionID,
AnswerDescription,
CreatedDate,
ROW_NUMBER() OVER(PARTITION BY QuestionID
ORDER BY CreatedDate DESC) AS rn
FROM ANSWER) AS a
ON q.questionID = a.QuestionID AND
a.rn = 1
答案 1 :(得分:4)
获得每个问题,SQL Server 2005 +
SELECT
q.QuestionID, q.QuestionName,
a.AnswerDescription, a.CreatedDate
FROM
QUESTION q
CROSS APPLY
(
SELECT TOP 1 a2.AnswerDescription, a2.CreatedDate
FROM ANSWER a2
WHERE q.questionID = a2.QuestionID
ORDER BY a2.CreatedDate DESC
) a
答案 2 :(得分:0)
SELECT top 1 q.QuestionID, q.QuestionName, a.AnswerDescription, a.CreatedDate FROM QUESTION q
INNER JOIN ANSWER a
ON q.questionID = a.QuestionID
ORDER BY a.CreatedDate DESC