1

我有一个如下表:

Job    Quantity Status
-----------------------
1      100      OK
2      400      HOLD
3      200      HOLD
4      450      OK
5      300     
6      500      

我希望我的结果如下所示:

Job  Quantity Status
----------------------
4      450      OK
2      400      HOLD
1      100      OK
3      200      HOLD
6      500 
5      300

status我已经创建了这个查询,但是当表包含列为空/空的数据时它不起作用

SELECT 
    Job, 
    Quantity, 
    Status 
FROM 
    myTable
ORDER BY CASE 
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 2 
    WHEN QUANTITY <  400 AND STATUS = 'OK' THEN 3 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 4 
    WHEN QUANTITY >= 400 AND STATUS = '' THEN 5 
    WHEN QUANTITY <  400 AND STATUS = '' THEN 6 
END
4

2 回答 2

6

除非我误读,否则我觉得您已经回答了自己的问题。您需要说明您的数据何时为NULL.

重要的部分是它NULL的类型不同于''. 就像'' = 0是假的一样,也是NULL = ''NULL用于表示空值。用布尔值而不是字符串来考虑它。显然,有时某些东西既不是真也不是假,这就是价值 likeNULL的来源。类似地,如果您将字符串视为纯数据而不是字符和单词,那么空值和无值之间存在差异全部。

有关详细信息,请参阅http://www.w3schools.com/sql/sql_null_values.asp

所以我认为你的代码应该是这样的:

SELECT Job, Quantity, Status 
    FROM myTable
ORDER BY CASE 
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD'  THEN 2 
    WHEN QUANTITY < 400 AND STATUS = 'OK'  THEN 3 
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD'  THEN 4 
    WHEN QUANTITY >= 400 AND (STATUS = '' OR STATUS IS NULL)  THEN 5 
    WHEN QUANTITY < 400 AND (STATUS = '' OR STATUS IS NULL)  THEN 6
END

除非您明确将 STATUS 设置为'',否则您可能只能使用STATUS IS NULL.

于 2012-05-29T04:31:18.677 回答
3

尝试使用以下查询:-

SELECT  
    Job,  
    Quantity,  
    Status  
FROM  
    myTable 
ORDER BY CASE  
    WHEN QUANTITY >= 400 AND STATUS = 'OK' THEN 1  
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 2  
    WHEN QUANTITY <  400 AND STATUS = 'OK' THEN 3  
    WHEN QUANTITY >= 400 AND STATUS = 'HOLD' THEN 4  
    WHEN QUANTITY >= 400 AND COALESCE(STATUS,'') = '' THEN 5  
    WHEN QUANTITY <  400 AND COALESCE(STATUS,'') = '' THEN 6  
END 

COALESCE()函数返回第一个非空参数,因此如果STATUSNULL它将返回''

http://www.sqlbook.com/SQL/SQL-Coalesce-28.aspx

于 2012-05-29T07:58:38.217 回答