问题
I can't understand why this doesn't work:
select distinct a.QuestionID,a.QuestionName,b.AnswerID,b.AnswerName
from @TempExportList a
join tblAnswers b
on a.QuestionID = b.QuestionID
where a.PaperID=@PaperID
order by (case when a.QuestionName='A' then 0
when a.QuestionName='B' then 1
else a.QuestionID
end)
I get the following error -
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
But this works fine:
select distinct a.QuestionID,a.QuestionName,b.AnswerID,b.AnswerName
from @TempExportList a
join tblAnswers b
on a.QuestionID = b.QuestionID
where a.PaperID=@PaperID
order by a.QuestionID
回答1:
The error message explains the problem perfectly.
In the first example the ORDER BY
item -- CASE WHEN ... END
-- doesn't appear in the SELECT
list.
In the second example the ORDER BY
item -- a.QuestionID
-- does appear in the SELECT
list.
To fix the first example you'll need to do something like this:
SELECT DISTINCT a.QuestionID, a.QuestionName, b.AnswerID, b.AnswerName,
CASE WHEN a.QuestionName = 'A' THEN 0
WHEN a.QuestionName = 'B' THEN 1
ELSE a.QuestionID
END
FROM @TempExportList AS a
JOIN tblAnswers AS b
ON a.QuestionID = b.QuestionID
WHERE a.PaperID = @PaperID
ORDER BY CASE WHEN a.QuestionName = 'A' THEN 0
WHEN a.QuestionName = 'B' THEN 1
ELSE a.QuestionID
END
回答2:
You can get around this with a CTE
;WITH T AS
(
SELECT DISTINCT a.QuestionID,a.QuestionName,b.AnswerID,b.AnswerName
FROM @TempExportList a
JOIN tblAnswers b
ON a.QuestionID = b.QuestionID
WHERE a.PaperID=@PaperID
)
SELECT *
FROM T
ORDER BY
CASE
WHEN QuestionName='A'
THEN 0
WHEN QuestionName='B'
THEN 1
ELSE QuestionID
END
回答3:
I would have thought the message self explanitory.
You have selected a distinct on a.QuestionID,a.QuestionName,b.AnswerID and b.AnswerName. Therefore, there could be rows of data with the same respective values for each of these fields, but a different one for your case
statement.
Consider this
a.QuestionID a.QuestionName b.AnswerID b.AnswerName [case statement]
1 'One' 2 'Two' 0
1 'One' 2 'Two' 1
How does the query know which value in the last column to use in the order? Is it 0? It is 1? Quite simply, it can't determine, so it can't use it, hence the error.
The second example is fine, because a.QuestionID does appear in the SELECT list, and the query can happily apply the ordering.
来源:https://stackoverflow.com/questions/4335374/sql-custom-order-by