SQL Distinct / Order By error

时间:2011-02-03 17:10:30

标签: sql sql-server sql-server-2008 distinct

使用“order by”时出现问题&同时“不同”。例如,我有以下内容:

DECLARE @fieldSort varchar(100) = 'ref'

SELECT DISTINCT EXT_Design_Standard_ID
FROM EXT_Design_Standard_Change_Log
ORDER BY CASE 
     WHEN @fieldSort ='REF' THEN 
          EXT_Design_Standard_ID 
     END

我收到错误:

  

如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

任何人都知道如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

在子选择中执行DISTINCT,在外部选择中执行ORDER BY

SELECT * from (SELECT distinct... ) order by ...

答案 1 :(得分:0)

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

或使用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