我正在使用SQL Server 2008。
我有一个问题表,我有一个答案表。问题表包含QuestionID,Question和Position(order)。 Answers表包含Answers和AnswerID。每个问题都可以多次回答。
我们的顾问应该只看到最近的答案,这就是我们按答案ID DESC排序的原因。
我们的管理员需要能够查看每个答案的历史记录。这就是为什么我们不删除答案。
我的查询现在看起来像这样:
SELECT Q.*, A.*
FROM Questions Q
LEFT JOIN Answers A
ON Q.QuestionID = A.QuestionID
WHERE FranchisorID = 10
ORDER BY Q.Position, A.AnswerID DESC
上面查询的结果集如下所示:
QuestionID - Question - AnswerID - Answer -
1 what is your fave color? 3 Blue
1 what is your fave color? 2 Green
1 what is your fave color? 1 Red
4 What year is this? 5 2011
4 What year is this? 4 2010
我需要将结果集看起来像这样:
1 what is your fave color? 3 Blue
4 What year is this? 5 2011
你能为我调整一下我的小查询吗?
答案 0 :(得分:2)
一种选择是
QuestionID
ORDER BY DESC
AnswerID
只返回最大的AnswerID
rn = 1
SELECT *
FROM (
SELECT Q.QuestionID
, Q.Question
, A.AnwerID
, A.Answer
, rn = ROW_NUMBER() OVER (PARTITION BY QuestionID ORDER BY AnswerID DESC)
FROM Questions Q
LEFT JOIN Answers A ON Q.QuestionID = A.QuestionID
WHERE FranchisorID = 10
) r
WHERE r.rn = 1
答案 1 :(得分:1)
使用INNER JOIN
到CTE过滤结果。
WITH LatestAnswer AS
(
SELECT QuestionID,
MAX(AnswerID) AS LatestAnswerID
FROM Questions
INNER JOIN Answers ON Answers.QuestionID = Questions.QuestionID
GROUP BY QuestionID
)
SELECT Q.*, A.*
FROM Questions Q
LEFT JOIN Answers A ON Q.QuestionID = A.QuestionID
INNER JOIN LatestAnswer ON LatestAnswer.LatestAnswerID = Answers.AnswerID
WHERE FranchisorID = 10
ORDER BY Q.Position, A.AnswerID DESC
答案 2 :(得分:0)
SELECT Q.*, A.*
FROM Questions Q
LEFT JOIN Answers A
ON A.AnswerId in
(select top 1 a2.AnswerId from Answers a2
where a2.QuestionId=Q.QuestionId order by a2.AnswerId DESC)
WHERE FranchisorID = 10
ORDER BY Q.Position