ORDER BY CASE WHEN:ORDER BY项目必须出现在选择列表中

时间:2016-11-14 20:28:53

标签: sql-order-by union case-when

我有一些我试图运行的示例代码。只更改了表名和列名。我想要做的是拥有状态的结果集并且具有“空”'是第一个值,其余结果显示在' NULL'按升序排列,我不能让我的生活变得有效。我在底部得到错误。这可能是一个非常" noobish"问题,但任何人都可以帮忙吗?非常感谢所有人!

SELECT  DISTINCT
    State
FROM    TABLE1 (NOLOCK)
WHERE   COLUMN1 NOT LIKE '%THAT%'
    AND COLUMN1 NOT LIKE '%THIS%'
UNION
SELECT  'NULL'
ORDER BY ( CASE WHEN State = 'NULL' THEN 0
            ELSE 1
       END );   

错误讯息:

ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

1 个答案:

答案 0 :(得分:0)

您需要选择该列...即使您以后不使用它,订单也要求它出现在选择中。

SELECT  DISTINCT
    State,
 CASE WHEN State = 'NULL' THEN 0
            ELSE 1 END orderId
FROM    TABLE1 (NOLOCK)
WHERE   COLUMN1 NOT LIKE '%THAT%'
    AND COLUMN1 NOT LIKE '%THIS%'
ORDER BY ( CASE WHEN State = 'NULL' THEN 0
            ELSE 1
       END );