开发者

SQL Distinct /Order By error

开发者 https://www.devze.com 2023-02-08 03:48 出处:网络
I\'ve got a problem when using \"order by\" & \"distinct\" at the same time. For example, I have the following:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消