查询执行失败并显示错误如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中

时间:2016-02-16 07:30:45

标签: sql-server-2014 sql-server-2014-express

您好我正在使用Microsoft SQL Server 2014(SP1-CU4)

SELECT DISTINCT A.PI_LOOKUP_CATEGORY_ID,  
    REPLACE(REPLACE(UPPER(A.LOOKUP_CATEGORY_NAME), ' ', '_'), '-', '_') AS CATEGORY_TECH_NAME, 
    A.LOOKUP_CATEGORY_NAME, 
    A.LOOKUP_CATEGORY_DESCR,
    COUNT(B.PI_LOOKUP_CATEGORY_ID) AS USAGE_COUNT
    FROM [PI_LOOKUP_CATEGORY] A LEFT OUTER JOIN [PI_INSIGHT_COLUMN] B ON 
    A.PI_LOOKUP_CATEGORY_ID = B.PI_LOOKUP_CATEGORY_ID
    GROUP BY A.PI_LOOKUP_CATEGORY_ID,  
    REPLACE(REPLACE(UPPER(A.LOOKUP_CATEGORY_NAME), ' ', '_'), '-', '_'), 
    A.LOOKUP_CATEGORY_NAME, 
    A.LOOKUP_CATEGORY_DESCR
    ORDER BY REPLACE(REPLACE(UPPER(A.LOOKUP_CATEGORY_NAME), ' ', '_'), '-', '_')

上面的查询失败并出现错误"查询执行失败并显示错误如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。"

相同的查询与较低版本的sql服务器(如2008R2,2012等)

一起正常工作

请通过SQL Server 2014告诉我们此问题的解决方案。

1 个答案:

答案 0 :(得分:0)

尝试

 SELECT DISTINCT A.PI_LOOKUP_CATEGORY_ID,
             REPLACE(REPLACE(UPPER(A.LOOKUP_CATEGORY_NAME), ' ', ''), '-', '') AS CATEGORY_TECH_NAME, 
             A.LOOKUP_CATEGORY_NAME, A.LOOKUP_CATEGORY_DESCR, 
             COUNT(B.PI_LOOKUP_CATEGORY_ID) AS USAGE_COUNT 
FROM [PI_LOOKUP_CATEGORY] A 
LEFT OUTER JOIN [PI_INSIGHT_COLUMN] B ON A.PI_LOOKUP_CATEGORY_ID = B.PI_LOOKUP_CATEGORY_ID 
GROUP BY A.PI_LOOKUP_CATEGORY_ID, 
         REPLACE(REPLACE(UPPER(A.LOOKUP_CATEGORY_NAME), ' ', ''), '-', ''), 
         A.LOOKUP_CATEGORY_NAME, 
         A.LOOKUP_CATEGORY_DESCR 
ORDER BY CATEGORY_TECH_NAME