SQL Distinct /Order By error
I've got a problem when using "order by" & "distinct" at the same time. For example, I have the following:
DECLARE @fieldSort varchar(100) = 'ref'
SELECT DISTINCT EXT_Design_Standard_ID
FROM EXT_Design_Standard_Change_Log
ORDER BY CASE开发者_StackOverflow中文版
WHEN @fieldSort ='REF' THEN
EXT_Design_Standard_ID
END
I get the error of:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
Anyone know how to sort this out?
Do the DISTINCT in a subselect and the ORDER BY in the outer select
SELECT * from (SELECT distinct... ) order by ...
DECLARE @fieldSort varchar(100) = 'ref';
with cte As
(
SELECT distinct EXT_Design_Standard_ID
from EXT_Design_Standard_Change_Log
)
SELECT *
FROM cte
ORDER BY
CASE WHEN @fieldSort ='REF'
THEN EXT_Design_Standard_ID END
Or use GROUP BY
SELECT EXT_Design_Standard_ID
FROM EXT_Design_Standard_Change_Log
GROUP BY EXT_Design_Standard_ID
ORDER BY
CASE WHEN @fieldSort ='REF'
THEN EXT_Design_Standard_ID END
精彩评论